--- python2.7-2.7.15.orig/debian/2to3-2.7.1 +++ python2.7-2.7.15/debian/2to3-2.7.1 @@ -0,0 +1,41 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.40.4. +.TH 2TO3-2.7 "1" "January 2012" "2to3-2.7 2.7" "User Commands" +.SH NAME +2to3-2.7 \- Python2 to Python3 converter +.SH SYNOPSIS +.B 2to3 +[\fIoptions\fR] \fIfile|dir \fR... +.SH OPTIONS +.TP +\fB\-h\fR, \fB\-\-help\fR +show this help message and exit +.TP +\fB\-d\fR, \fB\-\-doctests_only\fR +Fix up doctests only +.TP +\fB\-f\fR FIX, \fB\-\-fix\fR=\fIFIX\fR +Each FIX specifies a transformation; default: all +.TP +\fB\-j\fR PROCESSES, \fB\-\-processes\fR=\fIPROCESSES\fR +Run 2to3 concurrently +.TP +\fB\-x\fR NOFIX, \fB\-\-nofix\fR=\fINOFIX\fR +Prevent a transformation from being run +.TP +\fB\-l\fR, \fB\-\-list\-fixes\fR +List available transformations +.TP +\fB\-p\fR, \fB\-\-print\-function\fR +Modify the grammar so that print() is a function +.TP +\fB\-v\fR, \fB\-\-verbose\fR +More verbose logging +.TP +\fB\-\-no\-diffs\fR +Don't show diffs of the refactoring +.TP +\fB\-w\fR, \fB\-\-write\fR +Write back modified files +.TP +\fB\-n\fR, \fB\-\-nobackups\fR +Don't write backups for modified files --- python2.7-2.7.15.orig/debian/FAQ.html +++ python2.7-2.7.15/debian/FAQ.html @@ -0,0 +1,8997 @@ + + +The Whole Python FAQ + + + +

The Whole Python FAQ

+Last changed on Wed Feb 12 21:31:08 2003 CET + +

(Entries marked with ** were changed within the last 24 hours; +entries marked with * were changed within the last 7 days.) +

+ +

+


+

1. General information and availability

+ + +

+


+

2. Python in the real world

+ + +

+


+

3. Building Python and Other Known Bugs

+ + +

+


+

4. Programming in Python

+ + +

+


+

5. Extending Python

+ + +

+


+

6. Python's design

+ + +

+


+

7. Using Python on non-UNIX platforms

+ + +

+


+

8. Python on Windows

+ + +
+

1. General information and availability

+ +
+

1.1. What is Python?

+Python is an interpreted, interactive, object-oriented programming +language. It incorporates modules, exceptions, dynamic typing, very +high level dynamic data types, and classes. Python combines +remarkable power with very clear syntax. It has interfaces to many +system calls and libraries, as well as to various window systems, and +is extensible in C or C++. It is also usable as an extension language +for applications that need a programmable interface. Finally, Python +is portable: it runs on many brands of UNIX, on the Mac, and on PCs +under MS-DOS, Windows, Windows NT, and OS/2. +

+To find out more, the best thing to do is to start reading the +tutorial from the documentation set (see a few questions further +down). +

+See also question 1.17 (what is Python good for). +

+ +Edit this entry / +Log info + +/ Last changed on Mon May 26 16:05:18 1997 by +GvR +

+ +


+

1.2. Why is it called Python?

+Apart from being a computer scientist, I'm also a fan of "Monty +Python's Flying Circus" (a BBC comedy series from the seventies, in +the -- unlikely -- case you didn't know). It occurred to me one day +that I needed a name that was short, unique, and slightly mysterious. +And I happened to be reading some scripts from the series at the +time... So then I decided to call my language Python. +

+By now I don't care any more whether you use a Python, some other +snake, a foot or 16-ton weight, or a wood rat as a logo for Python! +

+ +Edit this entry / +Log info + +/ Last changed on Thu Aug 24 00:50:41 2000 by +GvR +

+ +


+

1.3. How do I obtain a copy of the Python source?

+The latest Python source distribution is always available from +python.org, at http://www.python.org/download. The latest development sources can be obtained via anonymous CVS from SourceForge, at http://www.sf.net/projects/python . +

+The source distribution is a gzipped tar file containing the complete C source, LaTeX +documentation, Python library modules, example programs, and several +useful pieces of freely distributable software. This will compile and +run out of the box on most UNIX platforms. (See section 7 for +non-UNIX information.) +

+Older versions of Python are also available from python.org. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Apr 9 17:06:16 2002 by +A.M. Kuchling +

+ +


+

1.4. How do I get documentation on Python?

+All documentation is available on-line, starting at http://www.python.org/doc/. +

+The LaTeX source for the documentation is part of the source +distribution. If you don't have LaTeX, the latest Python +documentation set is available, in various formats like postscript +and html, by anonymous ftp - visit the above URL for links to the +current versions. +

+PostScript for a high-level description of Python is in the file nluug-paper.ps +(a separate file on the ftp site). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jan 21 12:02:55 1998 by +Ken Manheimer +

+ +


+

1.5. Are there other ftp sites that mirror the Python distribution?

+The following anonymous ftp sites keep mirrors of the Python +distribution: +

+USA: +

+

+        ftp://ftp.python.org/pub/python/
+        ftp://gatekeeper.dec.com/pub/plan/python/
+        ftp://ftp.uu.net/languages/python/
+        ftp://ftp.wustl.edu/graphics/graphics/sgi-stuff/python/
+        ftp://ftp.sterling.com/programming/languages/python/
+        ftp://uiarchive.cso.uiuc.edu/pub/lang/python/
+        ftp://ftp.pht.com/mirrors/python/python/
+	ftp://ftp.cdrom.com/pub/python/
+
+Europe: +

+

+        ftp://ftp.cwi.nl/pub/python/
+        ftp://ftp.funet.fi/pub/languages/python/
+        ftp://ftp.sunet.se/pub/lang/python/
+        ftp://unix.hensa.ac.uk/mirrors/uunet/languages/python/
+        ftp://ftp.lip6.fr/pub/python/
+        ftp://sunsite.cnlab-switch.ch/mirror/python/
+        ftp://ftp.informatik.tu-muenchen.de/pub/comp/programming/languages/python/
+
+Australia: +

+

+        ftp://ftp.dstc.edu.au/pub/python/
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Mar 24 09:20:49 1999 by +A.M. Kuchling +

+ +


+

1.6. Is there a newsgroup or mailing list devoted to Python?

+There is a newsgroup, comp.lang.python, +and a mailing list. The newsgroup and mailing list are gatewayed into +each other -- if you can read news it's unnecessary to subscribe to +the mailing list. To subscribe to the mailing list +(python-list@python.org) visit its Mailman webpage at +http://www.python.org/mailman/listinfo/python-list +

+More info about the newsgroup and mailing list, and about other lists, +can be found at +http://www.python.org/psa/MailingLists.html. +

+Archives of the newsgroup are kept by Deja News and accessible +through the "Python newsgroup search" web page, +http://www.python.org/search/search_news.html. +This page also contains pointer to other archival collections. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jun 23 09:29:36 1999 by +GvR +

+ +


+

1.7. Is there a WWW page devoted to Python?

+Yes, http://www.python.org/ is the official Python home page. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 14:42:59 1997 by +Ken Manheimer +

+ +


+

1.8. Is the Python documentation available on the WWW?

+Yes. Python 2.0 documentation is available from +http://www.pythonlabs.com/tech/python2.0/doc/ and from +http://www.python.org/doc/. Note that most documentation +is available for on-line browsing as well as for downloading. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 03:14:08 2001 by +Moshe Zadka +

+ +


+

1.9. Are there any books on Python?

+Yes, many, and more are being published. See +the python.org Wiki at http://www.python.org/cgi-bin/moinmoin/PythonBooks for a list. +

+You can also search online bookstores for "Python" +(and filter out the Monty Python references; or +perhaps search for "Python" and "language"). +

+ +Edit this entry / +Log info + +/ Last changed on Mon Aug 5 19:08:49 2002 by +amk +

+ +


+

1.10. Are there any published articles about Python that I can reference?

+If you can't reference the web site, and you don't want to reference the books +(see previous question), there are several articles on Python that you could +reference. +

+Most publications about Python are collected on the Python web site: +

+

+    http://www.python.org/doc/Publications.html
+
+It is no longer recommended to reference this +very old article by Python's author: +

+

+    Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
+    Servers Using the Python Programming Language", CWI Quarterly, Volume
+    4, Issue 4 (December 1991), Amsterdam, pp 283-303.
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sat Jul 4 20:52:31 1998 by +GvR +

+ +


+

1.11. Are there short introductory papers or talks on Python?

+There are several - you can find links to some of them collected at +http://www.python.org/doc/Hints.html#intros. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 15:04:05 1997 by +Ken Manheimer +

+ +


+

1.12. How does the Python version numbering scheme work?

+Python versions are numbered A.B.C or A.B. A is the major version +number -- it is only incremented for really major changes in the +language. B is the minor version number, incremented for less +earth-shattering changes. C is the micro-level -- it is +incremented for each bugfix release. See PEP 6 for more information +about bugfix releases. +

+Not all releases have bugfix releases. +Note that in the past (ending with 1.5.2), +micro releases have added significant changes; +in fact the changeover from 0.9.9 to 1.0.0 was the first time +that either A or B changed! +

+Alpha, beta and release candidate versions have an additional suffixes. +The suffix for an alpha version is "aN" for some small number N, the +suffix for a beta version is "bN" for some small number N, and the +suffix for a release candidate version is "cN" for some small number N. +

+Note that (for instance) all versions labeled 2.0aN precede the +versions labeled 2.0bN, which precede versions labeled 2.0cN, and +those precede 2.0. +

+As a rule, no changes are made between release candidates and the final +release unless there are show-stopper bugs. +

+You may also find version numbers with a "+" suffix, e.g. "2.2+". +These are unreleased versions, built directly from the CVS trunk. +

+See also the documentation for sys.version, sys.hexversion, and +sys.version_info. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 14 06:34:17 2002 by +GvR +

+ +


+

1.13. How do I get a beta test version of Python?

+All releases, including alphas, betas and release candidates, are announced on +comp.lang.python and comp.lang.python.announce newsgroups, +which are gatewayed into the python-list@python.org and +python-announce@python.org. In addition, all these announcements appear on +the Python home page, at http://www.python.org. +

+You can also access the development version of Python through CVS. See http://sourceforge.net/cvs/?group_id=5470 for details. If you're not familiar with CVS, documents like http://linux.oreillynet.com/pub/a/linux/2002/01/03/cvs_intro.html +provide an introduction. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 00:57:08 2002 by +Neal Norwitz +

+ +


+

1.14. Are there copyright restrictions on the use of Python?

+Hardly. You can do anything you want with the source, as long as +you leave the copyrights in, and display those copyrights in any +documentation about Python that you produce. Also, don't use the +author's institute's name in publicity without prior written +permission, and don't hold them responsible for anything (read the +actual copyright for a precise legal wording). +

+In particular, if you honor the copyright rules, it's OK to use Python +for commercial use, to sell copies of Python in source or binary form, +or to sell products that enhance Python or incorporate Python (or part +of it) in some form. I would still like to know about all commercial +use of Python! +

+ +Edit this entry / +Log info +

+ +


+

1.15. Why was Python created in the first place?

+Here's a very brief summary of what got me started: +

+I had extensive experience with implementing an interpreted language +in the ABC group at CWI, and from working with this group I had +learned a lot about language design. This is the origin of many +Python features, including the use of indentation for statement +grouping and the inclusion of very-high-level data types (although the +details are all different in Python). +

+I had a number of gripes about the ABC language, but also liked many +of its features. It was impossible to extend the ABC language (or its +implementation) to remedy my complaints -- in fact its lack of +extensibility was one of its biggest problems. +I had some experience with using Modula-2+ and talked with the +designers of Modula-3 (and read the M3 report). M3 is the origin of +the syntax and semantics used for exceptions, and some other Python +features. +

+I was working in the Amoeba distributed operating system group at +CWI. We needed a better way to do system administration than by +writing either C programs or Bourne shell scripts, since Amoeba had +its own system call interface which wasn't easily accessible from the +Bourne shell. My experience with error handling in Amoeba made me +acutely aware of the importance of exceptions as a programming +language feature. +

+It occurred to me that a scripting language with a syntax like ABC +but with access to the Amoeba system calls would fill the need. I +realized that it would be foolish to write an Amoeba-specific +language, so I decided that I needed a language that was generally +extensible. +

+During the 1989 Christmas holidays, I had a lot of time on my hand, +so I decided to give it a try. During the next year, while still +mostly working on it in my own time, Python was used in the Amoeba +project with increasing success, and the feedback from colleagues made +me add many early improvements. +

+In February 1991, after just over a year of development, I decided +to post to USENET. The rest is in the Misc/HISTORY file. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 00:06:23 1997 by +GvR +

+ +


+

1.16. Do I have to like "Monty Python's Flying Circus"?

+No, but it helps. Pythonistas like the occasional reference to SPAM, +and of course, nobody expects the Spanish Inquisition +

+The two main reasons to use Python are: +

+

+ - Portable
+ - Easy to learn
+
+The three main reasons to use Python are: +

+

+ - Portable
+ - Easy to learn
+ - Powerful standard library
+
+(And nice red uniforms.) +

+And remember, there is no rule six. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 28 10:39:21 1997 by +GvR +

+ +


+

1.17. What is Python good for?

+Python is used in many situations where a great deal of dynamism, +ease of use, power, and flexibility are required. +

+In the area of basic text +manipulation core Python (without any non-core extensions) is easier +to use and is roughly as fast as just about any language, and this makes Python +good for many system administration type tasks and for CGI programming +and other application areas that manipulate text and strings and such. +

+When augmented with +standard extensions (such as PIL, COM, Numeric, oracledb, kjbuckets, +tkinter, win32api, etc.) +or special purpose extensions (that you write, perhaps using helper tools such +as SWIG, or using object protocols such as ILU/CORBA or COM) Python +becomes a very convenient "glue" or "steering" +language that helps make heterogeneous collections of unrelated +software packages work together. +For example by combining Numeric with oracledb you can help your +SQL database do statistical analysis, or even Fourier transforms. +One of the features that makes Python excel in the "glue language" role +is Python's simple, usable, and powerful C language runtime API. +

+Many developers also use Python extensively as a graphical user +interface development aide. +

+ +Edit this entry / +Log info + +/ Last changed on Sat May 24 10:13:11 1997 by +Aaron Watters +

+ +


+

1.18. Can I use the FAQ Wizard software to maintain my own FAQ?

+Sure. It's in Tools/faqwiz/ of the python source tree. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Mar 29 06:50:32 2002 by +Aahz +

+ +


+

1.19. Which editor has good support for editing Python source code?

+On Unix, the first choice is Emacs/XEmacs. There's an elaborate +mode for editing Python code, which is available from the Python +source distribution (Misc/python-mode.el). It's also bundled +with XEmacs (we're still working on legal details to make it possible +to bundle it with FSF Emacs). And it has its own web page: +

+

+    http://www.python.org/emacs/python-mode/index.html
+
+There are many other choices, for Unix, Windows or Macintosh. +Richard Jones compiled a table from postings on the Python newsgroup: +

+

+    http://www.bofh.asn.au/~richard/editors.html
+
+See also FAQ question 7.10 for some more Mac and Win options. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 15 23:21:04 1998 by +Gvr +

+ +


+

1.20. I've never programmed before. Is there a Python tutorial?

+There are several, and at least one book. +All information for beginning Python programmers is collected here: +

+

+    http://www.python.org/doc/Newbies.html
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Sep 5 05:34:07 2001 by +GvR +

+ +


+

1.21. Where in the world is www.python.org located?

+It's currently in Amsterdam, graciously hosted by XS4ALL: +

+

+    http://www.xs4all.nl
+
+Thanks to Thomas Wouters for setting this up!!!! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 3 21:49:27 2001 by +GvR +

+ +


+

2. Python in the real world

+ +
+

2.1. How many people are using Python?

+Certainly thousands, and quite probably tens of thousands of users. +More are seeing the light each day. The comp.lang.python newsgroup is +very active, but overall there is no accurate estimate of the number of subscribers or Python users. +

+Jacek Artymiak has created a Python Users Counter; you can see the +current count by visiting +http://www.wszechnica.safenet.pl/cgi-bin/checkpythonuserscounter.py +(this will not increment the counter; use the link there if you haven't +added yourself already). Most Python users appear not to have registered themselves. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Feb 21 23:29:18 2002 by +GvR +

+ +


+

2.2. Have any significant projects been done in Python?

+At CWI (the former home of Python), we have written a 20,000 line +authoring environment for transportable hypermedia presentations, a +5,000 line multimedia teleconferencing tool, as well as many many +smaller programs. +

+At CNRI (Python's new home), we have written two large applications: +Grail, a fully featured web browser (see +http://grail.cnri.reston.va.us), +and the Knowbot Operating Environment, +a distributed environment for mobile code. +

+The University of Virginia uses Python to control a virtual reality +engine. See http://alice.cs.cmu.edu. +

+The ILU project at Xerox PARC can generate Python glue for ILU +interfaces. See ftp://ftp.parc.xerox.com/pub/ilu/ilu.html. ILU +is a free CORBA compliant ORB which supplies distributed object +connectivity to a host of platforms using a host of languages. +

+Mark Hammond and Greg Stein and others are interfacing Python to +Microsoft's COM and ActiveX architectures. This means, among other +things, that Python may be used in active server pages or as a COM +controller (for example to automatically extract from or insert information +into Excel or MSAccess or any other COM aware application). +Mark claims Python can even be a ActiveX scripting host (which +means you could embed JScript inside a Python application, if you +had a strange sense of humor). Python/AX/COM is distributed as part +of the PythonWin distribution. +

+The University of California, Irvine uses a student administration +system called TELE-Vision written entirely in Python. Contact: Ray +Price rlprice@uci.edu. +

+The Melbourne Cricket Ground (MCG) in Australia (a 100,000+ person venue) +has it's scoreboard system written largely in Python on MS Windows. +Python expressions are used to create almost every scoring entry that +appears on the board. The move to Python/C++ away from exclusive C++ +has provided a level of functionality that would simply not have been +viable otherwise. +

+See also the next question. +

+Note: this FAQ entry is really old. +See http://www.python.org/psa/Users.html for a more recent list. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Oct 25 13:24:15 2000 by +GvR +

+ +


+

2.3. Are there any commercial projects going on using Python?

+Yes, there's lots of commercial activity using Python. See +http://www.python.org/psa/Users.html for a list. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Oct 14 18:17:33 1998 by +ken +

+ +


+

2.4. How stable is Python?

+Very stable. New, stable releases have been coming out roughly every 3 to 12 months since 1991, and this seems likely to continue. +

+With the introduction of retrospective "bugfix" releases the stability of the language implementations can be, and is being, improved independently of the new features offered by more recent major or minor releases. Bugfix releases, indicated by a third component of the version number, only fix known problems and do not gratuitously introduce new and possibly incompatible features or modified library functionality. +

+Release 2.2 got its first bugfix on April 10, 2002. The new version +number is now 2.2.1. The 2.1 release, at 2.1.3, can probably be +considered the "most stable" platform because it has been bugfixed +twice. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jul 23 10:20:04 2002 by +Jens Kubieziel +

+ +


+

2.5. What new developments are expected for Python in the future?

+See http://www.python.org/peps/ for the Python Enhancement +Proposals (PEPs). PEPs are design +documents +describing a suggested new feature for Python, providing +a concise technical specification and a rationale. +

+Also, follow the discussions on the python-dev mailing list. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Apr 9 17:09:51 2002 by +A.M. Kuchling +

+ +


+

2.6. Is it reasonable to propose incompatible changes to Python?

+In general, no. There are already millions of lines of Python code +around the world, so any changes in the language that invalidates more +than a very small fraction of existing programs has to be frowned +upon. Even if you can provide a conversion program, there still is +the problem of updating all documentation. Providing a gradual +upgrade path is the only way if a feature has to be changed. +

+See http://www.python.org/peps/pep-0005.html for the proposed +mechanism for creating backwards-incompatibilities. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 1 22:13:47 2002 by +Fred Drake +

+ +


+

2.7. What is the future of Python?

+Please see http://www.python.org/peps/ for proposals of future +activities. One of the PEPs (Python Enhancement Proposals) deals +with the PEP process and PEP format -- see +http://www.python.org/peps/pep-0001.html if you want to +submit a PEP. In http://www.python.org/peps/pep-0042.html there +is a list of wishlists the Python Development team plans to tackle. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 1 22:15:46 2002 by +Fred Drake +

+ +


+

2.8. What was the PSA, anyway?

+The Python Software Activity was +created by a number of Python aficionados who want Python to be more +than the product and responsibility of a single individual. +The PSA was not an independent organization, but lived +under the umbrealla of CNRI. +

+The PSA has been superseded by the Python Software Foundation, +an independent non-profit organization. The PSF's home page +is at http://www.python.org/psf/. +

+Some pages created by the PSA still live at +http://www.python.org/psa/ +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 25 18:19:44 2002 by +GvR +

+ +


+

2.9. Deleted

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 02:51:30 2001 by +Moshe Zadka +

+ +


+

2.10. Deleted

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 02:52:19 2001 by +Moshe Zadka +

+ +


+

2.11. Is Python Y2K (Year 2000) Compliant?

+As of January, 2001 no major problems have been reported and Y2K +compliance seems to be a non-issue. +

+Since Python is available free of charge, there are no absolute +guarantees. If there are unforeseen problems, liability is the +user's rather than the developers', and there is nobody you can sue for damages. +

+Python does few +date manipulations, and what it does is all based on the Unix +representation for time (even on non-Unix systems) which uses seconds +since 1970 and won't overflow until 2038. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 8 17:19:32 2001 by +Steve Holden +

+ +


+

2.12. Is Python a good language in a class for beginning programmers?

+Yes. This long answer attempts to address any concerns you might +have with teaching Python as a programmer's first language. +(If you want to discuss Python's use in education, then +you may be interested in joining the edu-sig mailinglist. +See http://www.python.org/sigs/edu-sig/ ) +

+It is still common to start students with a procedural +(subset of a) statically typed language such as Pascal, C, or +a subset of C++ or Java. I think that students may be better +served by learning Python as their first language. Python has +a very simple and consistent syntax and a large standard library. +Most importantly, using Python in a beginning programming course +permits students to concentrate on important programming skills, +such as problem decomposition and data type design. +

+With Python, students can be quickly introduced to basic concepts +such as loops and procedures. They can even probably work with +user-defined objects in their very first course. They could +implement a tree structure as nested Python lists, for example. +They could be introduced to objects in their first course if +desired. For a student who has never programmed before, using +a statically typed language seems unnatural. It presents +additional complexity that the student must master and slows +the pace of the course. The students are trying to learn to +think like a computer, decompose problems, design consistent +interfaces, and encapsulate data. While learning to use a +statically typed language is important, it is not necessarily the +best topic to address in the students' first programming course. +

+Many other aspects of Python make it a good first language. +Python has a large standard library (like Java) so that +students can be assigned programming projects very early in the +course that do something. Assignments aren't restricted to the +standard four-function calculator and check balancing programs. +By using the standard library, students can gain the satisfaction +of working on realistic applications as they learn the fundamentals +of programming. Using the standard library also teaches students +about code reuse. +

+Python's interactive interpreter also enables students to +test language features while they're programming. They can keep +a window with the interpreter running while they enter their +programs' source in another window. If they can't remember the +methods for a list, they can do something like this: +

+

+ >>> L = []
+ >>> dir(L)
+ ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
+ 'reverse', 'sort']
+ >>> print L.append.__doc__
+ L.append(object) -- append object to end
+ >>> L.append(1)
+ >>> L
+ [1]
+
+With the interpreter, documentation is never far from the +student as he's programming. +

+There are also good IDEs for Python. Guido van Rossum's IDLE +is a cross-platform IDE for Python that is written in Python +using Tk. There is also a Windows specific IDE called PythonWin. +Emacs users will be happy to know that there is a very good Python +mode for Emacs. All of these programming environments provide +syntax highlighting, auto-indenting, and access to the interactive +interpreter while coding. For more information about IDEs, see XXX. +

+If your department is currently using Pascal because it was +designed to be a teaching language, then you'll be happy to +know that Guido van Rossum designed Python to be simple to +teach to everyone but powerful enough to implement real world +applications. Python makes a good language for first time +programmers because that was one of Python's design goals. +There are papers at http://www.python.org/doc/essays/ on the Python website +by Python's creator explaining his objectives for the language. +One that may interest you is titled "Computer Programming for Everybody" +http://www.python.org/doc/essays/cp4e.html +

+If you're seriously considering Python as a language for your +school, Guido van Rossum may even be willing to correspond with +you about how the language would fit in your curriculum. +See http://www.python.org/doc/FAQ.html#2.2 for examples of +Python's use in the "real world." +

+While Python, its source code, and its IDEs are freely +available, this consideration should not rule +out other languages. There are other free languages (Java, +free C compilers), and many companies are willing to waive some +or all of their fees for student programming tools if it +guarantees that a whole graduating class will know how to +use their tools. That is, if one of the requirements for +the language that will be taught is that it be freely +available, then Python qualifies, but this requirement +does not preclude other languages. +

+While Python jobs may not be as prevalent as C/C++/Java jobs, +teachers should not worry about teaching students critical job +skills in their first course. The skills that win students a +job are those they learn in their senior classes and internships. +Their first programming courses are there to lay a solid +foundation in programming fundamentals. The primary question +in choosing the language for such a course should be which +language permits the students to learn this material without +hindering or limiting them. +

+Another argument for Python is that there are many tasks for +which something like C++ is overkill. That's where languages +like Python, Perl, Tcl, and Visual Basic thrive. It's critical +for students to know something about these languages. (Every +employer for whom I've worked used at least one such language.) +Of the languages listed above, Python probably makes the best +language in a programming curriculum since its syntax is simple, +consistent, and not unlike other languages (C/C++/Java) that +are probably in the curriculum. By starting students with +Python, a department simultaneously lays the foundations for +other programming courses and introduces students to the type +of language that is often used as a "glue" language. As an +added bonus, Python can be used to interface with Microsoft's +COM components (thanks to Mark Hammond). There is also Jython, +a Java implementation of the Python interpreter, that can be +used to connect Java components. +

+If you currently start students with Pascal or C/C++ or Java, +you may be worried they will have trouble learning a statically +typed language after starting with Python. I think that this +fear most often stems from the fact that the teacher started +with a statically typed language, and we tend to like to teach +others in the same way we were taught. In reality, the +transition from Python to one of these other languages is +quite simple. +

+To motivate a statically typed language such as C++, begin the +course by explaining that unlike Python, their first language, +C++ is compiled to a machine dependent executable. Explain +that the point is to make a very fast executable. To permit +the compiler to make optimizations, programmers must help it +by specifying the "types" of variables. By restricting each +variable to a specific type, the compiler can reduce the +book-keeping it has to do to permit dynamic types. The compiler +also has to resolve references at compile time. Thus, the +language gains speed by sacrificing some of Python's dynamic +features. Then again, the C++ compiler provides type safety +and catches many bugs at compile time instead of run time (a +critical consideration for many commercial applications). C++ +is also designed for very large programs where one may want to +guarantee that others don't touch an object's implementation. +C++ provides very strong language features to separate an object's +implementation from its interface. Explain why this separation +is a good thing. +

+The first day of a C++ course could then be a whirlwind introduction +to what C++ requires and provides. The point here is that after +a semester or two of Python, students are hopefully competent +programmers. They know how to handle loops and write procedures. +They've also worked with objects, thought about the benefits of +consistent interfaces, and used the technique of subclassing to +specialize behavior. Thus, a whirlwind introduction to C++ could +show them how objects and subclassing looks in C++. The +potentially difficult concepts of object-oriented design were +taught without the additional obstacles presented by a language +such as C++ or Java. When learning one of these languages, +the students would already understand the "road map." They +understand objects; they would just be learning how objects +fit in a statically typed languages. Language requirements +and compiler errors that seem unnatural to beginning programmers +make sense in this new context. Many students will find it +helpful to be able to write a fast prototype of their algorithms +in Python. Thus, they can test and debug their ideas before +they attempt to write the code in the new language, saving the +effort of working with C++ types for when they've discovered a +working solution for their assignments. When they get annoyed +with the rigidity of types, they'll be happy to learn about +containers and templates to regain some of the lost flexibility +Python afforded them. Students may also gain an appreciation +for the fact that no language is best for every task. They'll +see that C++ is faster, but they'll know that they can gain +flexibility and development speed with a Python when execution +speed isn't critical. +

+If you have any concerns that weren't addressed here, try +posting to the Python newsgroup. Others there have done some +work with using Python as an instructional tool. Good luck. +We'd love to hear about it if you choose Python for your course. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 2 19:32:35 2002 by +Bill Sconce +

+ +


+

3. Building Python and Other Known Bugs

+ +
+

3.1. Is there a test set?

+Sure. You can run it after building with "make test", or you can +run it manually with this command at the Python prompt: +

+

+ import test.autotest
+
+In Python 1.4 or earlier, use +

+

+ import autotest
+
+The test set doesn't test all features of Python, +but it goes a long way to confirm that Python is actually working. +

+NOTE: if "make test" fails, don't just mail the output to the +newsgroup -- this doesn't give enough information to debug the +problem. Instead, find out which test fails, and run that test +manually from an interactive interpreter. For example, if +"make test" reports that test_spam fails, try this interactively: +

+

+ import test.test_spam
+
+This generally produces more verbose output which can be diagnosed +to debug the problem. If you find a bug in Python or the libraries, or in the tests, please report this in the Python bug tracker at SourceForge: +

+http://sourceforge.net/tracker/?func=add&group_id=5470&atid=105470 +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 27 10:29:36 2001 by +Fred Drake +

+ +


+

3.2. When running the test set, I get complaints about floating point operations, but when playing with floating point operations I cannot find anything wrong with them.

+The test set makes occasional unwarranted assumptions about the +semantics of C floating point operations. Until someone donates a +better floating point test set, you will have to comment out the +offending floating point tests and execute similar tests manually. +

+ +Edit this entry / +Log info +

+ +


+

3.3. Link errors after rerunning the configure script.

+It is generally necessary to run "make clean" after a configuration +change. +

+ +Edit this entry / +Log info +

+ +


+

3.4. The python interpreter complains about options passed to a script (after the script name).

+You are probably linking with GNU getopt, e.g. through -liberty. +Don't. The reason for the complaint is that GNU getopt, unlike System +V getopt and other getopt implementations, doesn't consider a +non-option to be the end of the option list. A quick (and compatible) +fix for scripts is to add "--" to the interpreter, like this: +

+

+        #! /usr/local/bin/python --
+
+You can also use this interactively: +

+

+        python -- script.py [options]
+
+Note that a working getopt implementation is provided in the Python +distribution (in Python/getopt.c) but not automatically used. +

+ +Edit this entry / +Log info +

+ +


+

3.5. When building on the SGI, make tries to run python to create glmodule.c, but python hasn't been built or installed yet.

+Comment out the line mentioning glmodule.c in Setup and build a +python without gl first; install it or make sure it is in your $PATH, +then edit the Setup file again to turn on the gl module, and make +again. You don't need to do "make clean"; you do need to run "make +Makefile" in the Modules subdirectory (or just run "make" at the +toplevel). +

+ +Edit this entry / +Log info +

+ +


+

3.6. I use VPATH but some targets are built in the source directory.

+On some systems (e.g. Sun), if the target already exists in the +source directory, it is created there instead of in the build +directory. This is usually because you have previously built without +VPATH. Try running "make clobber" in the source directory. +

+ +Edit this entry / +Log info +

+ +


+

3.7. Trouble building or linking with the GNU readline library.

+You can use the GNU readline library to improve the interactive user +interface: this gives you line editing and command history when +calling python interactively. Its sources are distributed with +Python (at least for 2.0). Uncomment the line +

+#readline readline.c -lreadline -ltermcap +

+in Modules/Setup. The configuration option --with-readline +is no longer supported, at least in Python 2.0. Some hints on +building and using the readline library: +On SGI IRIX 5, you may have to add the following +to rldefs.h: +

+

+        #ifndef sigmask
+        #define sigmask(sig) (1L << ((sig)-1))
+        #endif
+
+On some systems, you will have to add #include "rldefs.h" to the +top of several source files, and if you use the VPATH feature, you +will have to add dependencies of the form foo.o: foo.c to the +Makefile for several values of foo. +The readline library requires use of the termcap library. A +known problem with this is that it contains entry points which +cause conflicts with the STDWIN and SGI GL libraries. The STDWIN +conflict can be solved by adding a line saying '#define werase w_erase' to the +stdwin.h file (in the STDWIN distribution, subdirectory H). The +GL conflict has been solved in the Python configure script by a +hack that forces use of the static version of the termcap library. +Check the newsgroup gnu.bash.bug news:gnu.bash.bug for +specific problems with the readline library (I don't read this group +but I've been told that it is the place for readline bugs). +

+ +Edit this entry / +Log info + +/ Last changed on Sat Dec 2 18:23:48 2000 by +Issac Trotts +

+ +


+

3.8. Trouble with socket I/O on older Linux 1.x versions.

+Once you've built Python, use it to run the regen script in the +Lib/plat-linux2 directory. Apparently the files as distributed don't match the system headers on some Linux versions. +

+Note that this FAQ entry only applies to Linux kernel versions 1.x.y; +these are hardly around any more. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jul 30 20:05:52 2002 by +Jens Kubieziel +

+ +


+

3.9. Trouble with prototypes on Ultrix.

+Ultrix cc seems broken -- use gcc, or edit config.h to #undef +HAVE_PROTOTYPES. +

+ +Edit this entry / +Log info +

+ +


+

3.10. Other trouble building Python on platform X.

+Please submit the details to the SourceForge bug tracker: +

+

+  http://sourceforge.net/tracker/?group_id=5470&atid=105470
+
+and we'll look +into it. Please provide as many details as possible. In particular, +if you don't tell us what type of computer and what operating system +(and version) you are using it will be difficult for us to figure out +what is the matter. If you have compilation output logs, +please use file uploads -- don't paste everything in the message box. +

+In many cases, we won't have access to the same hardware or operating system version, so please, if you have a SourceForge account, log in before filing your report, or if you don't have an account, include an email address at which we can reach you for further questions. Logging in to SourceForge first will also cause SourceForge to send you updates as we act on your report. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 27 10:53:18 2001 by +Fred Drake +

+ +


+

3.11. How to configure dynamic loading on Linux.

+This is now automatic as long as your Linux version uses the ELF +object format (all recent Linuxes do). +

+ +Edit this entry / +Log info +

+ +


+

3.12. I can't get shared modules to work on Linux 2.0 (Slackware96)?

+This is a bug in the Slackware96 release. The fix is simple: Make sure +that there is a link from /lib/libdl.so to /lib/libdl.so.1 so that the +following links are setup: /lib/libdl.so -> /lib/libdl.so.1 +/lib/libdl.so.1 -> /lib/libdl.so.1.7.14 You may have to rerun the +configure script, after rm'ing the config.cache file, before you +attempt to rebuild python after this fix. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 15:45:03 1997 by +GvR +

+ +


+

3.13. Trouble when making modules shared on Linux.

+This happens when you have built Python for static linking and then +enable +
+  *shared*
+
+in the Setup file. Shared library code must be +compiled with "-fpic". If a .o file for the module already exist that +was compiled for static linking, you must remove it or do "make clean" +in the Modules directory. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 13:42:30 1997 by +GvR +

+ +


+

3.14. [deleted]

+[ancient information on threads on linux (when thread support +was not standard) used to be here] +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 2 17:27:13 2002 by +Erno Kuusela +

+ +


+

3.15. Errors when linking with a shared library containing C++ code.

+Link the main Python binary with C++. Change the definition of +LINKCC in Modules/Makefile to be your C++ compiler. You may have to +edit config.c slightly to make it compilable with C++. +

+ +Edit this entry / +Log info +

+ +


+

3.16. Deleted

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 11 16:02:22 2001 by +GvR +

+ +


+

3.17. Deleted.

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 11 15:54:57 2001 by +GvR +

+ +


+

3.18. Compilation or link errors for the _tkinter module

+Most likely, there's a version mismatch between the Tcl/Tk header +files (tcl.h and tk.h) and the Tcl/Tk libraries you are using e.g. +"-ltk8.0" and "-ltcl8.0" arguments for _tkinter in the Setup file). +It is possible to install several versions of the Tcl/Tk libraries, +but there can only be one version of the tcl.h and tk.h header +files. If the library doesn't match the header, you'll get +problems, either when linking the module, or when importing it. +Fortunately, the version number is clearly stated in each file, +so this is easy to find. Reinstalling and using the latest +version usually fixes the problem. +

+(Also note that when compiling unpatched Python 1.5.1 against +Tcl/Tk 7.6/4.2 or older, you get an error on Tcl_Finalize. See +the 1.5.1 patch page at http://www.python.org/1.5/patches-1.5.1/.) +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 11 00:49:14 1998 by +Gvr +

+ +


+

3.19. I configured and built Python for Tcl/Tk but "import Tkinter" fails.

+Most likely, you forgot to enable the line in Setup that says +"TKPATH=:$(DESTLIB)/tkinter". +

+ +Edit this entry / +Log info +

+ +


+

3.20. [deleted]

+[ancient information on a gcc+tkinter bug on alpha was here] +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 16:46:23 2002 by +Erno Kuusela +

+ +


+

3.21. Several common system calls are missing from the posix module.

+Most likely, all test compilations run by the configure script +are failing for some reason or another. Have a look in config.log to +see what could be the reason. A common reason is specifying a +directory to the --with-readline option that doesn't contain the +libreadline.a file. +

+ +Edit this entry / +Log info +

+ +


+

3.22. ImportError: No module named string, on MS Windows.

+Most likely, your PYTHONPATH environment variable should be set to +something like: +

+set PYTHONPATH=c:\python;c:\python\lib;c:\python\scripts +

+(assuming Python was installed in c:\python) +

+ +Edit this entry / +Log info +

+ +


+

3.23. Core dump on SGI when using the gl module.

+There are conflicts between entry points in the termcap and curses +libraries and an entry point in the GL library. There's a hack of a +fix for the termcap library if it's needed for the GNU readline +library, but it doesn't work when you're using curses. Concluding, +you can't build a Python binary containing both the curses and gl +modules. +

+ +Edit this entry / +Log info +

+ +


+

3.24. "Initializer not a constant" while building DLL on MS-Windows

+Static type object initializers in extension modules may cause compiles to +fail with an error message like "initializer not a constant". +Fredrik Lundh <Fredrik.Lundh@image.combitech.se> explains: +

+This shows up when building DLL under MSVC. There's two ways to +address this: either compile the module as C++, or change your code to +something like: +

+

+  statichere PyTypeObject bstreamtype = {
+      PyObject_HEAD_INIT(NULL) /* must be set by init function */
+      0,
+      "bstream",
+      sizeof(bstreamobject),
+
+
+  ...
+
+
+  void
+  initbstream()
+  {
+      /* Patch object type */
+      bstreamtype.ob_type = &PyType_Type;
+      Py_InitModule("bstream", functions);
+      ...
+  }
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sun May 25 14:58:05 1997 by +Aaron Watters +

+ +


+

3.25. Output directed to a pipe or file disappears on Linux.

+Some people have reported that when they run their script +interactively, it runs great, but that when they redirect it +to a pipe or file, no output appears. +

+

+    % python script.py
+    ...some output...
+    % python script.py >file
+    % cat file
+    % # no output
+    % python script.py | cat
+    % # no output
+    %
+
+This was a bug in Linux kernel. It is fixed and should not appear anymore. So most Linux users are not affected by this. +

+If redirection doesn't work on your Linux system, check what shell you are using. Shells like (t)csh doesn't support redirection. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jan 16 13:38:30 2003 by +Jens Kubieziel +

+ +


+

3.26. [deleted]

+[ancient libc/linux problem was here] +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 16:48:08 2002 by +Erno Kuusela +

+ +


+

3.27. [deleted]

+[ancient linux + threads + tk problem was described here] +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 16:49:08 2002 by +Erno Kuusela +

+ +


+

3.28. How can I test if Tkinter is working?

+Try the following: +

+

+  python
+  >>> import _tkinter
+  >>> import Tkinter
+  >>> Tkinter._test()
+
+This should pop up a window with two buttons, +one "Click me" and one "Quit". +

+If the first statement (import _tkinter) fails, your Python +installation probably has not been configured to support Tcl/Tk. +On Unix, if you have installed Tcl/Tk, you have to rebuild Python +after editing the Modules/Setup file to enable the _tkinter module +and the TKPATH environment variable. +

+It is also possible to get complaints about Tcl/Tk version +number mismatches or missing TCL_LIBRARY or TK_LIBRARY +environment variables. These have to do with Tcl/Tk installation +problems. +

+A common problem is to have installed versions of tcl.h and tk.h +that don't match the installed version of the Tcl/Tk libraries; +this usually results in linker errors or (when using dynamic +loading) complaints about missing symbols during loading +the shared library. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Aug 28 17:01:46 1997 by +Guido van Rossum +

+ +


+

3.29. Is there a way to get the interactive mode of the python interpreter to perform function/variable name completion?

+(From a posting by Guido van Rossum) +

+On Unix, if you have enabled the readline module (i.e. if Emacs-style +command line editing and bash-style history works for you), you can +add this by importing the undocumented standard library module +"rlcompleter". When completing a simple identifier, it +completes keywords, built-ins and globals in __main__; when completing +NAME.NAME..., it evaluates (!) the expression up to the last dot and +completes its attributes. +

+This way, you can do "import string", type "string.", hit the +completion key twice, and see the list of names defined by the +string module. +

+Tip: to use the tab key as the completion key, call +

+

+    readline.parse_and_bind("tab: complete")
+
+You can put this in a ~/.pythonrc file, and set the PYTHONSTARTUP +environment variable to ~/.pythonrc. This will cause the completion to be enabled +whenever you run Python interactively. +

+Notes (see the docstring for rlcompleter.py for more information): +

+* The evaluation of the NAME.NAME... form may cause arbitrary +application defined code to be executed if an object with a +__getattr__ hook is found. Since it is the responsibility of the +application (or the user) to enable this feature, I consider this an +acceptable risk. More complicated expressions (e.g. function calls or +indexing operations) are not evaluated. +

+* GNU readline is also used by the built-in functions input() and +raw_input(), and thus these also benefit/suffer from the complete +features. Clearly an interactive application can benefit by +specifying its own completer function and using raw_input() for all +its input. +

+* When stdin is not a tty device, GNU readline is never +used, and this module (and the readline module) are silently inactive. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 12 09:55:24 1998 by +A.M. Kuchling +

+ +


+

3.30. Why is the Python interpreter not built as a shared library?

+(This is a Unix question; on Mac and Windows, it is a shared +library.) +

+It's just a nightmare to get this to work on all different platforms. +Shared library portability is a pain. And yes, I know about GNU libtool +-- but it requires me to use its conventions for filenames etc, and it +would require a complete and utter rewrite of all the makefile and +config tools I'm currently using. +

+In practice, few applications embed Python -- it's much more common to +have Python extensions, which already are shared libraries. Also, +serious embedders often want total control over which Python version +and configuration they use so they wouldn't want to use a standard +shared library anyway. So while the motivation of saving space +when lots of apps embed Python is nice in theory, I +doubt that it will save much in practice. (Hence the low priority I +give to making a shared library.) +

+For Linux systems, the simplest method of producing libpython1.5.so seems to +be (originally from the Minotaur project web page, +http://www.equi4.com/minotaur/minotaur.html): +

+

+  make distclean 
+  ./configure 
+  make OPT="-fpic -O2" 
+  mkdir .extract 
+  (cd .extract; ar xv ../libpython1.5.a) 
+  gcc -shared -o libpython1.5.so .extract/*.o 
+  rm -rf .extract
+
+In Python 2.3 this will be supported by the standard build routine +(at least on Linux) with --enable-shared. Note however that there +is little advantage, and it slows down Python because of the need +for PIC code and the extra cost at startup time to find the library. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 30 13:36:55 2002 by +GvR +

+ +


+

3.31. Build with GCC on Solaris 2.6 (SunOS 5.6) fails

+If you have upgraded Solaris 2.5 or 2.5.1 to Solaris 2.6, +but you have not upgraded +your GCC installation, the compile may fail, e.g. like this: +

+

+ In file included from /usr/include/sys/stream.h:26,
+                  from /usr/include/netinet/in.h:38,
+                  from /usr/include/netdb.h:96,
+                  from ./socketmodule.c:121:
+ /usr/include/sys/model.h:32: #error "No DATAMODEL_NATIVE specified"
+
+Solution: rebuild GCC for Solaris 2.6. +You might be able to simply re-run fixincludes, but +people have had mixed success with doing that. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Oct 21 11:18:46 1998 by +GvR +

+ +


+

3.32. Running "make clean" seems to leave problematic files that cause subsequent builds to fail.

+Use "make clobber" instead. +

+Use "make clean" to reduce the size of the source/build directory +after you're happy with your build and installation. +If you have already tried to build python and you'd like to start +over, you should use "make clobber". It does a "make clean" and also +removes files such as the partially built Python library from a previous build. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 24 20:39:26 1999 by +TAB +

+ +


+

3.33. Submitting bug reports and patches

+To report a bug or submit a patch, please use the relevant service +from the Python project at SourceForge. +

+Bugs: http://sourceforge.net/tracker/?group_id=5470&atid=105470 +

+Patches: http://sourceforge.net/tracker/?group_id=5470&atid=305470 +

+If you have a SourceForge account, please log in before submitting your bug report; this will make it easier for us to contact you regarding your report in the event we have follow-up questions. It will also enable SourceForge to send you update information as we act on your bug. If you do not have a SourceForge account, please consider leaving your name and email address as part of the report. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 27 10:58:26 2001 by +Fred Drake +

+ +


+

3.34. I can't load shared libraries under Python 1.5.2, Solaris 7, and gcc 2.95.2

+When trying to load shared libraries, you may see errors like: +ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/lib/python1.5/site-packages/Perp/util/du_SweepUtilc.so: +
+ symbol PyExc_RuntimeError: referenced symbol not found
+
+

+There is a problem with the configure script for Python 1.5.2 +under Solaris 7 with gcc 2.95 . configure should set the make variable +LINKFORSHARED=-Xlinker -export-dynamic +

+

+in Modules/Makefile, +

+Manually add this line to the Modules/Makefile. +This builds a Python executable that can load shared library extensions (xxx.so) . +

+ +Edit this entry / +Log info + +/ Last changed on Mon Feb 19 10:37:05 2001 by +GvR +

+ +


+

3.35. In the regression test, test___all__ fails for the profile module. What's wrong?

+If you have been using the profile module, and have properly calibrated a copy of the module as described in the documentation for the profiler: +

+http://www.python.org/doc/current/lib/profile-calibration.html +

+then it is possible that the regression test "test___all__" will fail if you run the regression test manually rather than using "make test" in the Python source directory. This will happen if you have set your PYTHONPATH environment variable to include the directory containing your calibrated profile module. You have probably calibrated the profiler using an older version of the profile module which does not define the __all__ value, added to the module as of Python 2.1. +

+The problem can be fixed by removing the old calibrated version of the profile module and using the latest version to do a fresh calibration. In general, you will need to re-calibrate for each version of Python anyway, since the performance characteristics can change in subtle ways that impact profiling. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 27 10:44:10 2001 by +Fred Drake +

+ +


+

3.36. relocations remain against allocatable but non-writable sections

+This linker error occurs on Solaris if you attempt to build an extension module which incorporates position-dependent (non-PIC) code. A common source of problems is that a static library (.a file), such as libreadline.a or libcrypto.a is linked with the extension module. The error specifically occurs when using gcc as the compiler, but /usr/ccs/bin/ld as the linker. +

+The following solutions and work-arounds are known: +

+1. Rebuild the libraries (libreadline, libcrypto) with -fPIC (-KPIC if using the system compiler). This is recommended; all object files in a shared library should be position-independent. +

+2. Statically link the extension module and its libraries into the Python interpreter, by editing Modules/Setup. +

+3. Use GNU ld instead of /usr/ccs/bin/ld; GNU ld will accept non-PIC code in shared libraries (and mark the section writable) +

+4. Pass -mimpure-text to GCC when linking the module. This will force gcc to not pass -z text to ld; in turn, ld will make all text sections writable. +

+Options 3 and 4 are not recommended, since the ability to share code across processes is lost. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 29 12:05:11 2002 by +Martin v. Löwis +

+ +


+

4. Programming in Python

+ +
+

4.1. Is there a source code level debugger with breakpoints, step, etc.?

+Yes. +

+Module pdb is a rudimentary but adequate console-mode debugger for Python. It is part of the standard Python library, and is documented in the Library Reference Manual. (You can also write your own debugger by using the code for pdb as an example.) +

+The IDLE interactive development environment, which is part of the standard Python distribution (normally available in Tools/idle), includes a graphical debugger. There is documentation for the IDLE debugger at http://www.python.org/idle/doc/idle2.html#Debugger +

+Pythonwin is a Python IDE that includes a GUI debugger based on bdb. The Pythonwin debugger colors breakpoints and has quite a few cool features (including debugging non-Pythonwin programs). A reference can be found at http://www.python.org/ftp/python/pythonwin/pwindex.html +More recent versions of PythonWin are available as a part of the ActivePython distribution (see http://www.activestate.com/Products/ActivePython/index.html). +

+Pydb is a version of the standard Python debugger pdb, modified for use with DDD (Data Display Debugger), a popular graphical debugger front end. Pydb can be found at http://packages.debian.org/unstable/devel/pydb.html +and DDD can be found at http://www.gnu.org/software/ddd/ +

+There are a number of commmercial Python IDEs that include graphical debuggers. They include: +

+

+ * Wing IDE (http://wingide.com/) 
+ * Komodo IDE (http://www.activestate.com/Products/Komodo/)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 28 01:43:41 2003 by +Stephen Ferg +

+ +


+

4.2. Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)? (Also phrased as: Can I use a built-in type as base class?)

+In Python 2.2, you can inherit from builtin classes such as int, list, dict, etc. +

+In previous versions of Python, you can easily create a Python class which serves as a wrapper around a built-in object, e.g. (for dictionaries): +

+

+        # A user-defined class behaving almost identical
+        # to a built-in dictionary.
+        class UserDict:
+                def __init__(self): self.data = {}
+                def __repr__(self): return repr(self.data)
+                def __cmp__(self, dict):
+                        if type(dict) == type(self.data):
+                                return cmp(self.data, dict)
+                        else:
+                                return cmp(self.data, dict.data)
+                def __len__(self): return len(self.data)
+                def __getitem__(self, key): return self.data[key]
+                def __setitem__(self, key, item): self.data[key] = item
+                def __delitem__(self, key): del self.data[key]
+                def keys(self): return self.data.keys()
+                def items(self): return self.data.items()
+                def values(self): return self.data.values()
+                def has_key(self, key): return self.data.has_key(key)
+
+A2. See Jim Fulton's ExtensionClass for an example of a mechanism +which allows you to have superclasses which you can inherit from in +Python -- that way you can have some methods from a C superclass (call +it a mixin) and some methods from either a Python superclass or your +subclass. ExtensionClass is distributed as a part of Zope (see +http://www.zope.org), but will be phased out with Zope 3, since +Zope 3 uses Python 2.2 or later which supports direct inheritance +from built-in types. Here's a link to the original paper about +ExtensionClass: +http://debian.acm.ndsu.nodak.edu/doc/python-extclass/ExtensionClass.html +

+A3. The Boost Python Library (BPL, http://www.boost.org/libs/python/doc/index.html) +provides a way of doing this from C++ (i.e. you can inherit from an +extension class written in C++ using the BPL). +

+ +Edit this entry / +Log info + +/ Last changed on Tue May 28 21:09:52 2002 by +GvR +

+ +


+

4.3. Is there a curses/termcap package for Python?

+The standard Python source distribution comes with a curses module in +the Modules/ subdirectory, though it's not compiled by default (note +that this is not available in the Windows distribution -- there is +no curses module for Windows). +

+In Python versions before 2.0 the module only supported plain curses; +you couldn't use ncurses features like colors with it (though it would +link with ncurses). +

+In Python 2.0, the curses module has been greatly extended, starting +from Oliver Andrich's enhanced version, to provide many additional +functions from ncurses and SYSV curses, such as colour, alternative +character set support, pads, and mouse support. This means the +module is no longer compatible with operating systems that only +have BSD curses, but there don't seem to be any currently +maintained OSes that fall into this category. +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 23 20:24:06 2002 by +Tim Peters +

+ +


+

4.4. Is there an equivalent to C's onexit() in Python?

+For Python 2.0: The new atexit module provides a register function that +is similar to C's onexit. See the Library Reference for details. For +2.0 you should not assign to sys.exitfunc! +

+For Python 1.5.2: You need to import sys and assign a function to +sys.exitfunc, it will be called when your program exits, is +killed by an unhandled exception, or (on UNIX) receives a +SIGHUP or SIGTERM signal. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:14:55 2000 by +Bjorn Pettersen +

+ +


+

4.5. [deleted]

+[python used to lack nested scopes, it was explained here] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:18:22 2002 by +Erno Kuusela +

+ +


+

4.6. How do I iterate over a sequence in reverse order?

+If it is a list, the fastest solution is +

+

+        list.reverse()
+        try:
+                for x in list:
+                        "do something with x"
+        finally:
+                list.reverse()
+
+This has the disadvantage that while you are in the loop, the list +is temporarily reversed. If you don't like this, you can make a copy. +This appears expensive but is actually faster than other solutions: +

+

+        rev = list[:]
+        rev.reverse()
+        for x in rev:
+                <do something with x>
+
+If it's not a list, a more general but slower solution is: +

+

+        for i in range(len(sequence)-1, -1, -1):
+                x = sequence[i]
+                <do something with x>
+
+A more elegant solution, is to define a class which acts as a sequence +and yields the elements in reverse order (solution due to Steve +Majewski): +

+

+        class Rev:
+                def __init__(self, seq):
+                        self.forw = seq
+                def __len__(self):
+                        return len(self.forw)
+                def __getitem__(self, i):
+                        return self.forw[-(i + 1)]
+
+You can now simply write: +

+

+        for x in Rev(list):
+                <do something with x>
+
+Unfortunately, this solution is slowest of all, due to the method +call overhead... +

+ +Edit this entry / +Log info + +/ Last changed on Sun May 25 21:10:50 1997 by +GvR +

+ +


+

4.7. My program is too slow. How do I speed it up?

+That's a tough one, in general. There are many tricks to speed up +Python code; I would consider rewriting parts in C only as a last +resort. One thing to notice is that function and (especially) method +calls are rather expensive; if you have designed a purely OO interface +with lots of tiny functions that don't do much more than get or set an +instance variable or call another method, you may consider using a +more direct way, e.g. directly accessing instance variables. Also see +the standard module "profile" (described in the Library Reference +manual) which makes it possible to find out where +your program is spending most of its time (if you have some patience +-- the profiling itself can slow your program down by an order of +magnitude). +

+Remember that many standard optimization heuristics you +may know from other programming experience may well apply +to Python. For example it may be faster to send output to output +devices using larger writes rather than smaller ones in order to +avoid the overhead of kernel system calls. Thus CGI scripts +that write all output in "one shot" may be notably faster than +those that write lots of small pieces of output. +

+Also, be sure to use "aggregate" operations where appropriate. +For example the "slicing" feature allows programs to chop up +lists and other sequence objects in a single tick of the interpreter +mainloop using highly optimized C implementations. Thus to +get the same effect as +

+

+  L2 = []
+  for i in range[3]:
+       L2.append(L1[i])
+
+it is much shorter and far faster to use +

+

+  L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
+
+Note that the map() function, particularly used with +builtin methods or builtin functions can be a convenient +accelerator. For example to pair the elements of two +lists together: +

+

+  >>> map(None, [1,2,3], [4,5,6])
+  [(1, 4), (2, 5), (3, 6)]
+
+or to compute a number of sines: +

+

+  >>> map( math.sin, (1,2,3,4))
+  [0.841470984808, 0.909297426826, 0.14112000806,   -0.756802495308]
+
+The map operation completes very quickly in such cases. +

+Other examples of aggregate operations include the join and split +methods of string objects. For example if s1..s7 are large (10K+) strings then +"".join([s1,s2,s3,s4,s5,s6,s7]) may be far faster than +the more obvious s1+s2+s3+s4+s5+s6+s7, since the "summation" +will compute many subexpressions, whereas join does all +copying in one pass. For manipulating strings also consider the +regular expression libraries and the "substitution" operations +String % tuple and String % dictionary. Also be sure to use +the list.sort builtin method to do sorting, and see FAQ's 4.51 +and 4.59 for examples of moderately advanced usage -- list.sort beats +other techniques for sorting in all but the most extreme +circumstances. +

+There are many other aggregate operations +available in the standard libraries and in contributed libraries +and extensions. +

+Another common trick is to "push loops into functions or methods." +For example suppose you have a program that runs slowly and you +use the profiler (profile.run) to determine that a Python function ff +is being called lots of times. If you notice that ff +

+

+   def ff(x):
+       ...do something with x computing result...
+       return result
+
+tends to be called in loops like (A) +

+

+   list = map(ff, oldlist)
+
+or (B) +

+

+   for x in sequence:
+       value = ff(x)
+       ...do something with value...
+
+then you can often eliminate function call overhead by rewriting +ff to +

+

+   def ffseq(seq):
+       resultseq = []
+       for x in seq:
+           ...do something with x computing result...
+           resultseq.append(result)
+       return resultseq
+
+and rewrite (A) to +

+

+    list = ffseq(oldlist)
+
+and (B) to +

+

+    for value in ffseq(sequence):
+        ...do something with value...
+
+Other single calls ff(x) translate to ffseq([x])[0] with little +penalty. Of course this technique is not always appropriate +and there are other variants, which you can figure out. +

+You can gain some performance by explicitly storing the results of +a function or method lookup into a local variable. A loop like +

+

+    for key in token:
+        dict[key] = dict.get(key, 0) + 1
+
+resolves dict.get every iteration. If the method isn't going to +change, a faster implementation is +

+

+    dict_get = dict.get  # look up the method once
+    for key in token:
+        dict[key] = dict_get(key, 0) + 1
+
+Default arguments can be used to determine values once, at +compile time instead of at run time. This can only be done for +functions or objects which will not be changed during program +execution, such as replacing +

+

+    def degree_sin(deg):
+        return math.sin(deg * math.pi / 180.0)
+
+with +

+

+    def degree_sin(deg, factor = math.pi/180.0, sin = math.sin):
+        return sin(deg * factor)
+
+Because this trick uses default arguments for terms which should +not be changed, it should only be used when you are not concerned +with presenting a possibly confusing API to your users. +

+

+For an anecdote related to optimization, see +

+

+	http://www.python.org/doc/essays/list2str.html
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:03:54 2002 by +Neal Norwitz +

+ +


+

4.8. When I have imported a module, then edit it, and import it again (into the same Python process), the changes don't seem to take place. What is going on?

+For reasons of efficiency as well as consistency, Python only reads +the module file on the first time a module is imported. (Otherwise a +program consisting of many modules, each of which imports the same +basic module, would read the basic module over and over again.) To +force rereading of a changed module, do this: +

+

+        import modname
+        reload(modname)
+
+Warning: this technique is not 100% fool-proof. In particular, +modules containing statements like +

+

+        from modname import some_objects
+
+will continue to work with the old version of the imported objects. +

+ +Edit this entry / +Log info +

+ +


+

4.9. How do I find the current module name?

+A module can find out its own module name by looking at the +(predefined) global variable __name__. If this has the value +'__main__' you are running as a script. +

+ +Edit this entry / +Log info +

+ +


+

4.10. I have a module in which I want to execute some extra code when it is run as a script. How do I find out whether I am running as a script?

+See the previous question. E.g. if you put the following on the +last line of your module, main() is called only when your module is +running as a script: +

+

+        if __name__ == '__main__': main()
+
+

+ +Edit this entry / +Log info +

+ +


+

4.11. I try to run a program from the Demo directory but it fails with ImportError: No module named ...; what gives?

+This is probably an optional module (written in C!) which hasn't +been configured on your system. This especially happens with modules +like "Tkinter", "stdwin", "gl", "Xt" or "Xm". For Tkinter, STDWIN and +many other modules, see Modules/Setup.in for info on how to add these +modules to your Python, if it is possible at all. Sometimes you will +have to ftp and build another package first (e.g. Tcl and Tk for Tkinter). +Sometimes the module only works on specific platforms (e.g. gl only works +on SGI machines). +

+NOTE: if the complaint is about "Tkinter" (upper case T) and you have +already configured module "tkinter" (lower case t), the solution is +not to rename tkinter to Tkinter or vice versa. There is probably +something wrong with your module search path. Check out the value of +sys.path. +

+For X-related modules (Xt and Xm) you will have to do more work: they +are currently not part of the standard Python distribution. You will +have to ftp the Extensions tar file, i.e. +ftp://ftp.python.org/pub/python/src/X-extension.tar.gz and follow +the instructions there. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Feb 12 21:31:08 2003 by +Jens Kubieziel +

+ +


+

4.12. [deleted]

+[stdwin (long dead windowing library) entry deleted] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 08:30:13 2002 by +Erno Kuusela +

+ +


+

4.13. What GUI toolkits exist for Python?

+Depending on what platform(s) you are aiming at, there are several. +

+Currently supported solutions: +

+Cross-platform: +

+Tk: +

+There's a neat object-oriented interface to the Tcl/Tk widget set, +called Tkinter. It is part of the standard Python distribution and +well-supported -- all you need to do is build and install Tcl/Tk and +enable the _tkinter module and the TKPATH definition in Modules/Setup +when building Python. This is probably the easiest to install and +use, and the most complete widget set. It is also very likely that in +the future the standard Python GUI API will be based on or at least +look very much like the Tkinter interface. For more info about Tk, +including pointers to the source, see the Tcl/Tk home page at +http://www.scriptics.com. Tcl/Tk is now fully +portable to the Mac and Windows platforms (NT and 95 only); you need +Python 1.4beta3 or later and Tk 4.1patch1 or later. +

+wxWindows: +

+There's an interface to wxWindows called wxPython. wxWindows is a +portable GUI class library written in C++. It supports GTK, Motif, +MS-Windows and Mac as targets. Ports to other platforms are being +contemplated or have already had some work done on them. wxWindows +preserves the look and feel of the underlying graphics toolkit, and +there is quite a rich widget set and collection of GDI classes. +See the wxWindows page at http://www.wxwindows.org/ for more details. +wxPython is a python extension module that wraps many of the wxWindows +C++ classes, and is quickly gaining popularity amongst Python +developers. You can get wxPython as part of the source or CVS +distribution of wxWindows, or directly from its home page at +http://alldunn.com/wxPython/. +

+Gtk+: +

+PyGtk bindings for the Gtk+ Toolkit by James Henstridge exist; see ftp://ftp.daa.com.au/pub/james/python/. Note that there are two incompatible bindings. If you are using Gtk+ 1.2.x you should get the 0.6.x PyGtk bindings from +

+

+    ftp://ftp.gtk.org/pub/python/v1.2
+
+If you plan to use Gtk+ 2.0 with Python (highly recommended if you are just starting with Gtk), get the most recent distribution from +

+

+    ftp://ftp.gtk.org/pub/python/v2.0
+
+If you are adventurous, you can also check out the source from the Gnome CVS repository. Set your CVS directory to :pserver:anonymous@anoncvs.gnome.org:/cvs/gnome and check the gnome-python module out from the repository. +

+Other: +

+There are also bindings available for the Qt toolkit (PyQt), and for KDE (PyKDE); see http://www.thekompany.com/projects/pykde/. +

+For OpenGL bindings, see http://starship.python.net/~da/PyOpenGL. +

+Platform specific: +

+The Mac port has a rich and ever-growing set of modules that support +the native Mac toolbox calls. See the documentation that comes with +the Mac port. See ftp://ftp.python.org/pub/python/mac. Support +by Jack Jansen jack@cwi.nl. +

+Pythonwin by Mark Hammond (MHammond@skippinet.com.au) +includes an interface to the Microsoft Foundation +Classes and a Python programming environment using it that's written +mostly in Python. See http://www.python.org/windows/. +

+There's an object-oriented GUI based on the Microsoft Foundation +Classes model called WPY, supported by Jim Ahlstrom jim@interet.com. +Programs written in WPY run unchanged and with native look and feel on +Windows NT/95, Windows 3.1 (using win32s), and on Unix (using Tk). +Source and binaries for Windows and Linux are available in +ftp://ftp.python.org/pub/python/wpy/. +

+Obsolete or minority solutions: +

+There's an interface to X11, including the Athena and Motif widget +sets (and a few individual widgets, like Mosaic's HTML widget and +SGI's GL widget) available from +ftp://ftp.python.org/pub/python/src/X-extension.tar.gz. +Support by Sjoerd Mullender sjoerd@cwi.nl. +

+On top of the X11 interface there's the vpApp +toolkit by Per Spilling, now also maintained by Sjoerd Mullender +sjoerd@cwi.nl. See ftp://ftp.cwi.nl/pub/sjoerd/vpApp.tar.gz. +

+For SGI IRIX only, there are unsupported interfaces to the complete +GL (Graphics Library -- low level but very good 3D capabilities) as +well as to FORMS (a buttons-and-sliders-etc package built on top of GL +by Mark Overmars -- ftp'able from +ftp://ftp.cs.ruu.nl/pub/SGI/FORMS/). This is probably also +becoming obsolete, as OpenGL takes over (see above). +

+There's an interface to STDWIN, a platform-independent low-level +windowing interface for Mac and X11. This is totally unsupported and +rapidly becoming obsolete. The STDWIN sources are at +ftp://ftp.cwi.nl/pub/stdwin/. +

+There is an interface to WAFE, a Tcl interface to the X11 +Motif and Athena widget sets. WAFE is at +http://www.wu-wien.ac.at/wafe/wafe.html. +

+ +Edit this entry / +Log info + +/ Last changed on Mon May 13 21:40:39 2002 by +Skip Montanaro +

+ +


+

4.14. Are there any interfaces to database packages in Python?

+Yes! See the Database Topic Guide at +http://www.python.org/topics/database/ for details. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 4 20:12:19 2000 by +Barney Warplug +

+ +


+

4.15. Is it possible to write obfuscated one-liners in Python?

+Yes. See the following three examples, due to Ulf Bartelt: +

+

+        # Primes < 1000
+        print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
+        map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
+
+
+        # First 10 Fibonacci numbers
+        print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
+        range(10))
+
+
+        # Mandelbrot set
+        print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
+        Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
+        Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
+        i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
+        >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
+        64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
+        ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
+        #    \___ ___/  \___ ___/  |   |   |__ lines on screen
+        #        V          V      |   |______ columns on screen
+        #        |          |      |__________ maximum of "iterations"
+        #        |          |_________________ range on y axis
+        #        |____________________________ range on x axis
+
+Don't try this at home, kids! +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 15:48:33 1997 by +GvR +

+ +


+

4.16. Is there an equivalent of C's "?:" ternary operator?

+Not directly. In many cases you can mimic a?b:c with "a and b or +c", but there's a flaw: if b is zero (or empty, or None -- anything +that tests false) then c will be selected instead. In many cases you +can prove by looking at the code that this can't happen (e.g. because +b is a constant or has a type that can never be false), but in general +this can be a problem. +

+Tim Peters (who wishes it was Steve Majewski) suggested the following +solution: (a and [b] or [c])[0]. Because [b] is a singleton list it +is never false, so the wrong path is never taken; then applying [0] to +the whole thing gets the b or c that you really wanted. Ugly, but it +gets you there in the rare cases where it is really inconvenient to +rewrite your code using 'if'. +

+As a last resort it is possible to implement the "?:" operator as a function: +

+

+    def q(cond,on_true,on_false):
+        from inspect import isfunction
+
+
+        if cond:
+            if not isfunction(on_true): return on_true
+            else: return apply(on_true)
+        else:
+            if not isfunction(on_false): return on_false 
+            else: return apply(on_false)
+
+In most cases you'll pass b and c directly: q(a,b,c). To avoid evaluating b +or c when they shouldn't be, encapsulate them +within a lambda function, e.g.: q(a,lambda: b, lambda: c). +

+

+

+It has been asked why Python has no if-then-else expression, +since most language have one; it is a frequently requested feature. +

+There are several possible answers: just as many languages do +just fine without one; it can easily lead to less readable code; +no sufficiently "Pythonic" syntax has been discovered; a search +of the standard library found remarkably few places where using an +if-then-else expression would make the code more understandable. +

+Nevertheless, in an effort to decide once and for all whether +an if-then-else expression should be added to the language, +PEP 308 (http://www.python.org/peps/pep-0308.html) has been +put forward, proposing a specific syntax. The community can +now vote on this issue. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Feb 7 19:41:13 2003 by +David Goodger +

+ +


+

4.17. My class defines __del__ but it is not called when I delete the object.

+There are several possible reasons for this. +

+The del statement does not necessarily call __del__ -- it simply +decrements the object's reference count, and if this reaches zero +__del__ is called. +

+If your data structures contain circular links (e.g. a tree where +each child has a parent pointer and each parent has a list of +children) the reference counts will never go back to zero. You'll +have to define an explicit close() method which removes those +pointers. Please don't ever call __del__ directly -- __del__ should +call close() and close() should make sure that it can be called more +than once for the same object. +

+If the object has ever been a local variable (or argument, which is +really the same thing) to a function that caught an expression in an +except clause, chances are that a reference to the object still exists +in that function's stack frame as contained in the stack trace. +Normally, deleting (better: assigning None to) sys.exc_traceback will +take care of this. If a stack was printed for an unhandled +exception in an interactive interpreter, delete sys.last_traceback +instead. +

+There is code that deletes all objects when the interpreter exits, +but it is not called if your Python has been configured to support +threads (because other threads may still be active). You can define +your own cleanup function using sys.exitfunc (see question 4.4). +

+Finally, if your __del__ method raises an exception, a warning message is printed to sys.stderr. +

+

+Starting with Python 2.0, a garbage collector periodically reclaims the space used by most cycles with no external references. (See the "gc" module documentation for details.) There are, however, pathological cases where it can be expected to fail. Moreover, the garbage collector runs some time after the last reference to your data structure vanishes, so your __del__ method may be called at an inconvenient and random time. This is inconvenient if you're trying to reproduce a problem. Worse, the order in which object's __del__ methods are executed is arbitrary. +

+Another way to avoid cyclical references is to use the "weakref" module, which allows you to point to objects without incrementing their reference count. Tree data structures, for instance, should use weak references for their parent and sibling pointers (if they need them!). +

+Question 6.14 is intended to explain the new garbage collection algorithm. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 10 15:27:28 2002 by +Matthias Urlichs +

+ +


+

4.18. How do I change the shell environment for programs called using os.popen() or os.system()? Changing os.environ doesn't work.

+You must be using either a version of python before 1.4, or on a +(rare) system that doesn't have the putenv() library function. +

+Before Python 1.4, modifying the environment passed to subshells was +left out of the interpreter because there seemed to be no +well-established portable way to do it (in particular, some systems, +have putenv(), others have setenv(), and some have none at all). As +of Python 1.4, almost all Unix systems do have putenv(), and so does +the Win32 API, and thus the os module was modified so that changes to +os.environ are trapped and the corresponding putenv() call is made. +

+ +Edit this entry / +Log info +

+ +


+

4.19. What is a class?

+A class is the particular object type created by executing +a class statement. Class objects are used as templates, to create +instance objects, which embody both the data structure +(attributes) and program routines (methods) specific to a datatype. +

+A class can be based on one or more other classes, called its base +class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined +by inheritance. +

+The term "classic class" is used to refer to the original +class implementation in Python. One problem with classic +classes is their inability to use the built-in data types +(such as list and dictionary) as base classes. Starting +with Python 2.2 an attempt is in progress to unify user-defined +classes and built-in types. It is now possible to declare classes +that inherit from built-in types. +

+ +Edit this entry / +Log info + +/ Last changed on Mon May 27 01:31:21 2002 by +Steve Holden +

+ +


+

4.20. What is a method?

+A method is a function that you normally call as +x.name(arguments...) for some object x. The term is used for methods +of classes and class instances as well as for methods of built-in +objects. (The latter have a completely different implementation and +only share the way their calls look in Python code.) Methods of +classes (and class instances) are defined as functions inside the +class definition. +

+ +Edit this entry / +Log info +

+ +


+

4.21. What is self?

+Self is merely a conventional name for the first argument of a +method -- i.e. a function defined inside a class definition. A method +defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for +some instance x of the class in which the definition occurs; +the called method will think it is called as meth(x, a, b, c). +

+ +Edit this entry / +Log info +

+ +


+

4.22. What is an unbound method?

+An unbound method is a method defined in a class that is not yet +bound to an instance. You get an unbound method if you ask for a +class attribute that happens to be a function. You get a bound method +if you ask for an instance attribute. A bound method knows which +instance it belongs to and calling it supplies the instance automatically; +an unbound method only knows which class it wants for its first +argument (a derived class is also OK). Calling an unbound method +doesn't "magically" derive the first argument from the context -- you +have to provide it explicitly. +

+Trivia note regarding bound methods: each reference to a bound +method of a particular object creates a bound method object. If you +have two such references (a = inst.meth; b = inst.meth), they will +compare equal (a == b) but are not the same (a is not b). +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 6 18:07:25 1998 by +Clarence Gardner +

+ +


+

4.23. How do I call a method defined in a base class from a derived class that overrides it?

+If your class definition starts with "class Derived(Base): ..." +then you can call method meth defined in Base (or one of Base's base +classes) as Base.meth(self, arguments...). Here, Base.meth is an +unbound method (see previous question). +

+ +Edit this entry / +Log info +

+ +


+

4.24. How do I call a method from a base class without using the name of the base class?

+DON'T DO THIS. REALLY. I MEAN IT. It appears that you could call +self.__class__.__bases__[0].meth(self, arguments...) but this fails when +a doubly-derived method is derived from your class: for its instances, +self.__class__.__bases__[0] is your class, not its base class -- so +(assuming you are doing this from within Derived.meth) you would start +a recursive call. +

+Often when you want to do this you are forgetting that classes +are first class in Python. You can "point to" the class you want +to delegate an operation to either at the instance or at the +subclass level. For example if you want to use a "glorp" +operation of a superclass you can point to the right superclass +to use. +

+

+  class subclass(superclass1, superclass2, superclass3):
+      delegate_glorp = superclass2
+      ...
+      def glorp(self, arg1, arg2):
+            ... subclass specific stuff ...
+            self.delegate_glorp.glorp(self, arg1, arg2)
+       ...
+
+
+  class subsubclass(subclass):
+       delegate_glorp = superclass3
+       ...
+
+Note, however that setting delegate_glorp to subclass in +subsubclass would cause an infinite recursion on subclass.delegate_glorp. Careful! Maybe you are getting too fancy for your own good. Consider simplifying the design (?). +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jul 28 13:58:22 1997 by +aaron watters +

+ +


+

4.25. How can I organize my code to make it easier to change the base class?

+You could define an alias for the base class, assign the real base +class to it before your class definition, and use the alias throughout +your class. Then all you have to change is the value assigned to the +alias. Incidentally, this trick is also handy if you want to decide +dynamically (e.g. depending on availability of resources) which base +class to use. Example: +

+

+        BaseAlias = <real base class>
+        class Derived(BaseAlias):
+                def meth(self):
+                        BaseAlias.meth(self)
+                        ...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 15:49:57 1997 by +GvR +

+ +


+

4.26. How can I find the methods or attributes of an object?

+This depends on the object type. +

+For an instance x of a user-defined class, instance attributes are +found in the dictionary x.__dict__, and methods and attributes defined +by its class are found in x.__class__.__bases__[i].__dict__ (for i in +range(len(x.__class__.__bases__))). You'll have to walk the tree of +base classes to find all class methods and attributes. +

+Many, but not all built-in types define a list of their method names +in x.__methods__, and if they have data attributes, their names may be +found in x.__members__. However this is only a convention. +

+For more information, read the source of the standard (but +undocumented) module newdir. +

+ +Edit this entry / +Log info +

+ +


+

4.27. I can't seem to use os.read() on a pipe created with os.popen().

+os.read() is a low-level function which takes a file descriptor (a +small integer). os.popen() creates a high-level file object -- the +same type used for sys.std{in,out,err} and returned by the builtin +open() function. Thus, to read n bytes from a pipe p created with +os.popen(), you need to use p.read(n). +

+ +Edit this entry / +Log info +

+ +


+

4.28. How can I create a stand-alone binary from a Python script?

+Even though there are Python compilers being developed, +you probably don't need a real compiler, if all you want +is a stand-alone program. There are three solutions to that. +

+One is to use the freeze tool, which is included in the Python +source tree as Tools/freeze. It converts Python byte +code to C arrays. Using a C compiler, you can embed all +your modules into a new program, which is then linked +with the standard Python modules. +

+It works by scanning your source recursively for import statements +(in both forms) and looking for the modules in the standard Python path +as well as in the source directory (for built-in modules). It then +1 the modules written in Python to C code (array initializers +that can be turned into code objects using the marshal module) and +creates a custom-made config file that only contains those built-in +modules which are actually used in the program. It then compiles the +generated C code and links it with the rest of the Python interpreter +to form a self-contained binary which acts exactly like your script. +

+(Hint: the freeze program only works if your script's filename ends in +".py".) +

+There are several utilities which may be helpful. The first is Gordon McMillan's installer at +

+

+    http://www.mcmillan-inc.com/install1.html
+
+which works on Windows, Linux and at least some forms of Unix. +

+Another is Thomas Heller's py2exe (Windows only) at +

+

+    http://starship.python.net/crew/theller/py2exe/
+
+A third is Christian Tismer's SQFREEZE +(http://starship.python.net/crew/pirx/) which appends the byte code +to a specially-prepared Python interpreter, which +will find the byte code in executable. +

+A fourth is Fredrik Lundh's Squeeze +(http://www.pythonware.com/products/python/squeeze/). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jun 19 14:01:30 2002 by +Gordon McMillan +

+ +


+

4.29. What WWW tools are there for Python?

+See the chapters titled "Internet Protocols and Support" and +"Internet Data Handling" in the Library Reference +Manual. Python is full of good things which will help you build server-side and client-side web systems. +

+A summary of available frameworks is maintained by Paul Boddie at +

+

+    http://thor.prohosting.com/~pboddie/Python/web_modules.html
+
+Cameron Laird maintains a useful set of pages about Python web technologies at +

+

+   http://starbase.neosoft.com/~claird/comp.lang.python/web_python.html/
+
+There was a web browser written in Python, called Grail -- +see http://sourceforge.net/project/grail/. This project has been terminated; http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/grail/grail/README gives more details. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Nov 11 22:48:25 2002 by +GvR +

+ +


+

4.30. How do I run a subprocess with pipes connected to both input and output?

+Use the standard popen2 module. For example: +

+

+	import popen2
+	fromchild, tochild = popen2.popen2("command")
+	tochild.write("input\n")
+	tochild.flush()
+	output = fromchild.readline()
+
+Warning: in general, it is unwise to +do this, because you can easily cause a deadlock where your +process is blocked waiting for output from the child, while the child +is blocked waiting for input from you. This can be caused +because the parent expects the child to output more text than it does, +or it can be caused by data being stuck in stdio buffers due to lack +of flushing. The Python parent can of course explicitly flush the data +it sends to the child before it reads any output, but if the child is +a naive C program it can easily have been written to never explicitly +flush its output, even if it is interactive, since flushing is +normally automatic. +

+Note that a deadlock is also possible if you use popen3 to read +stdout and stderr. If one of the two is too large for the internal +buffer (increasing the buffersize does not help) and you read() +the other one first, there is a deadlock, too. +

+Note on a bug in popen2: unless your program calls wait() +or waitpid(), finished child processes are never removed, +and eventually calls to popen2 will fail because of a limit on +the number of child processes. Calling os.waitpid with the +os.WNOHANG option can prevent this; a good place to insert such +a call would be before calling popen2 again. +

+Another way to produce a deadlock: Call a wait() and there is +still more output from the program than what fits into the +internal buffers. +

+In many cases, all you really need is to run some data through a +command and get the result back. Unless the data is infinite in size, +the easiest (and often the most efficient!) way to do this is to write +it to a temporary file and run the command with that temporary file as +input. The standard module tempfile exports a function mktemp() which +generates unique temporary file names. +

+

+ import tempfile
+ import os
+ class Popen3:
+    """
+    This is a deadlock-save version of popen, that returns
+    an object with errorlevel, out (a string) and err (a string).
+    (capturestderr may not work under windows.)
+    Example: print Popen3('grep spam','\n\nhere spam\n\n').out
+    """
+    def __init__(self,command,input=None,capturestderr=None):
+        outfile=tempfile.mktemp()
+        command="( %s ) > %s" % (command,outfile)
+        if input:
+            infile=tempfile.mktemp()
+            open(infile,"w").write(input)
+            command=command+" <"+infile
+        if capturestderr:
+            errfile=tempfile.mktemp()
+            command=command+" 2>"+errfile
+        self.errorlevel=os.system(command) >> 8
+        self.out=open(outfile,"r").read()
+        os.remove(outfile)
+        if input:
+            os.remove(infile)
+        if capturestderr:
+            self.err=open(errfile,"r").read()
+            os.remove(errfile)
+
+Note that many interactive programs (e.g. vi) don't work well with +pipes substituted for standard input and output. You will have to use +pseudo ttys ("ptys") instead of pipes. There is some undocumented +code to use these in the library module pty.py -- I'm afraid you're on +your own here. +

+A different answer is a Python interface to Don Libes' "expect" +library. A Python extension that interfaces to expect is called "expy" +and available from +http://expectpy.sourceforge.net/. +

+A pure Python solution that works like expect is pexpect of Noah Spurrier. +A beta version is available from +http://pexpect.sourceforge.net/ +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 3 16:31:31 2002 by +Tobias Polzin +

+ +


+

4.31. How do I call a function if I have the arguments in a tuple?

+Use the built-in function apply(). For instance, +

+

+    func(1, 2, 3)
+
+is equivalent to +

+

+    args = (1, 2, 3)
+    apply(func, args)
+
+Note that func(args) is not the same -- it calls func() with exactly +one argument, the tuple args, instead of three arguments, the integers +1, 2 and 3. +

+In Python 2.0, you can also use extended call syntax: +

+f(*args) is equivalent to apply(f, args) +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 03:42:50 2001 by +Moshe Zadka +

+ +


+

4.32. How do I enable font-lock-mode for Python in Emacs?

+If you are using XEmacs 19.14 or later, any XEmacs 20, FSF Emacs 19.34 +or any Emacs 20, font-lock should work automatically for you if you +are using the latest python-mode.el. +

+If you are using an older version of XEmacs or Emacs you will need +to put this in your .emacs file: +

+

+        (defun my-python-mode-hook ()
+          (setq font-lock-keywords python-font-lock-keywords)
+          (font-lock-mode 1))
+        (add-hook 'python-mode-hook 'my-python-mode-hook)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 6 16:18:46 1998 by +Barry Warsaw +

+ +


+

4.33. Is there a scanf() or sscanf() equivalent?

+Not as such. +

+For simple input parsing, the easiest approach is usually to split +the line into whitespace-delimited words using string.split(), and to +convert decimal strings to numeric values using int(), +long() or float(). (Python's int() is 32-bit and its +long() is arbitrary precision.) string.split supports an optional +"sep" parameter which is useful if the line uses something other +than whitespace as a delimiter. +

+For more complicated input parsing, regular expressions (see module re) +are better suited and more powerful than C's sscanf(). +

+There's a contributed module that emulates sscanf(), by Steve Clift; +see contrib/Misc/sscanfmodule.c of the ftp site: +

+

+    http://www.python.org/ftp/python/contrib-09-Dec-1999/Misc/
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:07:51 2002 by +Neal Norwitz +

+ +


+

4.34. Can I have Tk events handled while waiting for I/O?

+Yes, and you don't even need threads! But you'll have to +restructure your I/O code a bit. Tk has the equivalent of Xt's +XtAddInput() call, which allows you to register a callback function +which will be called from the Tk mainloop when I/O is possible on a +file descriptor. Here's what you need: +

+

+        from Tkinter import tkinter
+        tkinter.createfilehandler(file, mask, callback)
+
+The file may be a Python file or socket object (actually, anything +with a fileno() method), or an integer file descriptor. The mask is +one of the constants tkinter.READABLE or tkinter.WRITABLE. The +callback is called as follows: +

+

+        callback(file, mask)
+
+You must unregister the callback when you're done, using +

+

+        tkinter.deletefilehandler(file)
+
+Note: since you don't know *how many bytes* are available for reading, +you can't use the Python file object's read or readline methods, since +these will insist on reading a predefined number of bytes. For +sockets, the recv() or recvfrom() methods will work fine; for other +files, use os.read(file.fileno(), maxbytecount). +

+ +Edit this entry / +Log info +

+ +


+

4.35. How do I write a function with output parameters (call by reference)?

+[Mark Lutz] The thing to remember is that arguments are passed by +assignment in Python. Since assignment just creates references to +objects, there's no alias between an argument name in the caller and +callee, and so no call-by-reference per se. But you can simulate it +in a number of ways: +

+1) By using global variables; but you probably shouldn't :-) +

+2) By passing a mutable (changeable in-place) object: +

+

+      def func1(a):
+          a[0] = 'new-value'     # 'a' references a mutable list
+          a[1] = a[1] + 1        # changes a shared object
+
+
+      args = ['old-value', 99]
+      func1(args)
+      print args[0], args[1]     # output: new-value 100
+
+3) By returning a tuple, holding the final values of arguments: +

+

+      def func2(a, b):
+          a = 'new-value'        # a and b are local names
+          b = b + 1              # assigned to new objects
+          return a, b            # return new values
+
+
+      x, y = 'old-value', 99
+      x, y = func2(x, y)
+      print x, y                 # output: new-value 100
+
+4) And other ideas that fall-out from Python's object model. For instance, it might be clearer to pass in a mutable dictionary: +

+

+      def func3(args):
+          args['a'] = 'new-value'     # args is a mutable dictionary
+          args['b'] = args['b'] + 1   # change it in-place
+
+
+      args = {'a':' old-value', 'b': 99}
+      func3(args)
+      print args['a'], args['b']
+
+5) Or bundle-up values in a class instance: +

+

+      class callByRef:
+          def __init__(self, **args):
+              for (key, value) in args.items():
+                  setattr(self, key, value)
+
+
+      def func4(args):
+          args.a = 'new-value'        # args is a mutable callByRef
+          args.b = args.b + 1         # change object in-place
+
+
+      args = callByRef(a='old-value', b=99)
+      func4(args)
+      print args.a, args.b
+
+
+   But there's probably no good reason to get this complicated :-).
+
+[Python's author favors solution 3 in most cases.] +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 8 23:49:46 1997 by +David Ascher +

+ +


+

4.36. Please explain the rules for local and global variables in Python.

+[Ken Manheimer] In Python, procedure variables are implicitly +global, unless they are assigned anywhere within the block. +In that case +they are implicitly local, and you need to explicitly declare them as +'global'. +

+Though a bit surprising at first, a moment's consideration explains +this. On one hand, requirement of 'global' for assigned vars provides +a bar against unintended side-effects. On the other hand, if global +were required for all global references, you'd be using global all the +time. Eg, you'd have to declare as global every reference to a +builtin function, or to a component of an imported module. This +clutter would defeat the usefulness of the 'global' declaration for +identifying side-effects. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 28 09:53:27 1998 by +GvR +

+ +


+

4.37. How can I have modules that mutually import each other?

+Suppose you have the following modules: +

+foo.py: +

+

+	from bar import bar_var
+	foo_var=1
+
+bar.py: +

+

+	from foo import foo_var
+	bar_var=2
+
+The problem is that the above is processed by the interpreter thus: +

+

+	main imports foo
+	Empty globals for foo are created
+	foo is compiled and starts executing
+	foo imports bar
+	Empty globals for bar are created
+	bar is compiled and starts executing
+	bar imports foo (which is a no-op since there already is a module named foo)
+	bar.foo_var = foo.foo_var
+	...
+
+The last step fails, because Python isn't done with interpreting foo yet and the global symbol dict for foo is still empty. +

+The same thing happens when you use "import foo", and then try to access "foo.one" in global code. +

+

+There are (at least) three possible workarounds for this problem. +

+Guido van Rossum recommends to avoid all uses of "from <module> import ..." (so everything from an imported module is referenced as <module>.<name>) and to place all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only. +

+

+Jim Roskind suggests the following order in each module: +

+

+ exports (globals, functions, and classes that don't need imported base classes)
+ import statements
+ active code (including globals that are initialized from imported values).
+
+Python's author doesn't like this approach much because the imports +appear in a strange place, but has to admit that it works. +

+

+

+Matthias Urlichs recommends to restructure your code so that the recursive import is not necessary in the first place. +

+

+These solutions are not mutually exclusive. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 06:52:51 2002 by +Matthias Urlichs +

+ +


+

4.38. How do I copy an object in Python?

+Try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can. +

+Dictionaries have a copy method. Sequences can be copied by slicing: +

+ new_l = l[:]
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:40:26 2002 by +Erno Kuusela +

+ +


+

4.39. How to implement persistent objects in Python? (Persistent == automatically saved to and restored from disk.)

+The library module "pickle" now solves this in a very general way +(though you still can't store things like open files, sockets or +windows), and the library module "shelve" uses pickle and (g)dbm to +create persistent mappings containing arbitrary Python objects. +For possibly better performance also look for the latest version +of the relatively recent cPickle module. +

+A more awkward way of doing things is to use pickle's little sister, +marshal. The marshal module provides very fast ways to store +noncircular basic Python types to files and strings, and back again. +Although marshal does not do fancy things like store instances or +handle shared references properly, it does run extremely fast. For +example loading a half megabyte of data may take less than a +third of a second (on some machines). This often beats doing +something more complex and general such as using gdbm with +pickle/shelve. +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 8 22:59:00 1997 by +David Ascher +

+ +


+

4.40. I try to use __spam and I get an error about _SomeClassName__spam.

+Variables with double leading underscore are "mangled" to provide a +simple but effective way to define class private variables. See the +chapter "New in Release 1.4" in the Python Tutorial. +

+ +Edit this entry / +Log info +

+ +


+

4.41. How do I delete a file? And other file questions.

+Use os.remove(filename) or os.unlink(filename); for documentation, +see the posix section of the library manual. They are the same, +unlink() is simply the Unix name for this function. In earlier +versions of Python, only os.unlink() was available. +

+To remove a directory, use os.rmdir(); use os.mkdir() to create one. +

+To rename a file, use os.rename(). +

+To truncate a file, open it using f = open(filename, "r+"), and use +f.truncate(offset); offset defaults to the current seek position. +(The "r+" mode opens the file for reading and writing.) +There's also os.ftruncate(fd, offset) for files opened with os.open() +-- for advanced Unix hacks only. +

+The shutil module also contains a number of functions to work on files +including copyfile, copytree, and rmtree amongst others. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:30:01 2000 by +Bjorn Pettersen +

+ +


+

4.42. How to modify urllib or httplib to support HTTP/1.1?

+Recent versions of Python (2.0 and onwards) support HTTP/1.1 natively. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 02:56:56 2001 by +Moshe Zadka +

+ +


+

4.43. Unexplicable syntax errors in compile() or exec.

+When a statement suite (as opposed to an expression) is compiled by +compile(), exec or execfile(), it must end in a newline. In some +cases, when the source ends in an indented block it appears that at +least two newlines are required. +

+ +Edit this entry / +Log info +

+ +


+

4.44. How do I convert a string to a number?

+For integers, use the built-in int() function, e.g. int('144') == 144. Similarly, long() converts from string to long integer, e.g. long('144') == 144L; and float() to floating-point, e.g. float('144') == 144.0. +

+Note that these are restricted to decimal interpretation, so +that int('0144') == 144 and int('0x144') raises ValueError. For Python +2.0 int takes the base to convert from as a second optional argument, so +int('0x144', 16) == 324. +

+For greater flexibility, or before Python 1.5, import the module +string and use the string.atoi() function for integers, +string.atol() for long integers, or string.atof() for +floating-point. E.g., +string.atoi('100', 16) == string.atoi('0x100', 0) == 256. +See the library reference manual section for the string module for +more details. +

+While you could use the built-in function eval() instead of +any of those, this is not recommended, because someone could pass you +a Python expression that might have unwanted side effects (like +reformatting your disk). It also has the effect of interpreting numbers +as Python expressions, so that e.g. eval('09') gives a syntax error +since Python regards numbers starting with '0' as octal (base 8). +

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:37:34 2000 by +Bjorn Pettersen +

+ +


+

4.45. How do I convert a number to a string?

+To convert, e.g., the number 144 to the string '144', use the +built-in function repr() or the backquote notation (these are +equivalent). If you want a hexadecimal or octal representation, use +the built-in functions hex() or oct(), respectively. For fancy +formatting, use the % operator on strings, just like C printf formats, +e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'. +See the library reference manual for details. +

+ +Edit this entry / +Log info +

+ +


+

4.46. How do I copy a file?

+There's the shutil module which contains a copyfile() +function that implements a copy loop; +it isn't good enough for the Macintosh, though: +it doesn't copy the resource fork and Finder info. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 02:59:40 2001 by +Moshe Zadka +

+ +


+

4.47. How do I check if an object is an instance of a given class or of a subclass of it?

+If you are developing the classes from scratch it might be better to +program in a more proper object-oriented style -- instead of doing a different +thing based on class membership, why not use a method and define the +method differently in different classes? +

+However, there are some legitimate situations +where you need to test for class membership. +

+In Python 1.5, you can use the built-in function isinstance(obj, cls). +

+The following approaches can be used with earlier Python versions: +

+An unobvious method is to raise the object +as an exception and to try to catch the exception with the class you're +testing for: +

+

+	def is_instance_of(the_instance, the_class):
+	    try:
+		raise the_instance
+	    except the_class:
+		return 1
+	    except:
+		return 0
+
+This technique can be used to distinguish "subclassness" +from a collection of classes as well +

+

+                try:
+                              raise the_instance
+                except Audible:
+                              the_instance.play(largo)
+                except Visual:
+                              the_instance.display(gaudy)
+                except Olfactory:
+                              sniff(the_instance)
+                except:
+                              raise ValueError, "dunno what to do with this!"
+
+This uses the fact that exception catching tests for class or subclass +membership. +

+A different approach is to test for the presence of a class attribute that +is presumably unique for the given class. For instance: +

+

+	class MyClass:
+	    ThisIsMyClass = 1
+	    ...
+
+
+	def is_a_MyClass(the_instance):
+	    return hasattr(the_instance, 'ThisIsMyClass')
+
+This version is easier to inline, and probably faster (inlined it +is definitely faster). The disadvantage is that someone else could cheat: +

+

+	class IntruderClass:
+	    ThisIsMyClass = 1    # Masquerade as MyClass
+	    ...
+
+but this may be seen as a feature (anyway, there are plenty of other ways +to cheat in Python). Another disadvantage is that the class must be +prepared for the membership test. If you do not "control the +source code" for the class it may not be advisable to modify the +class to support testability. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jan 2 15:16:04 1998 by +GvR +

+ +


+

4.48. What is delegation?

+Delegation refers to an object oriented technique Python programmers +may implement with particular ease. Consider the following: +

+

+  from string import upper
+
+
+  class UpperOut:
+        def __init__(self, outfile):
+              self.__outfile = outfile
+        def write(self, str):
+              self.__outfile.write( upper(str) )
+        def __getattr__(self, name):
+              return getattr(self.__outfile, name)
+
+Here the UpperOut class redefines the write method +to convert the argument string to upper case before +calling the underlying self.__outfile.write method, but +all other methods are delegated to the underlying +self.__outfile object. The delegation is accomplished +via the "magic" __getattr__ method. Please see the +language reference for more information on the use +of this method. +

+Note that for more general cases delegation can +get trickier. Particularly when attributes must be set +as well as gotten the class must define a __settattr__ +method too, and it must do so carefully. +

+The basic implementation of __setattr__ is roughly +equivalent to the following: +

+

+   class X:
+        ...
+        def __setattr__(self, name, value):
+             self.__dict__[name] = value
+        ...
+
+Most __setattr__ implementations must modify +self.__dict__ to store local state for self without +causing an infinite recursion. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:11:24 1997 by +aaron watters +

+ +


+

4.49. How do I test a Python program or component.

+We presume for the purposes of this question you are interested +in standalone testing, rather than testing your components inside +a testing framework. The best-known testing framework for Python +is the PyUnit module, maintained at +

+

+    http://pyunit.sourceforge.net/
+
+For standalone testing, it helps to write the program so that +it may be easily tested by using good modular design. +In particular your program +should have almost all functionality encapsulated in either functions +or class methods -- and this sometimes has the surprising and +delightful effect of making the program run faster (because +local variable accesses are faster than global accesses). +Furthermore the program should avoid depending on mutating +global variables, since this makes testing much more difficult to do. +

+The "global main logic" of your program may be as simple +as +

+

+  if __name__=="__main__":
+       main_logic()
+
+at the bottom of the main module of your program. +

+Once your program is organized as a tractable collection +of functions and class behaviours you should write test +functions that exercise the behaviours. A test suite +can be associated with each module which automates +a sequence of tests. This sounds like a lot of work, but +since Python is so terse and flexible it's surprisingly easy. +You can make coding much more pleasant and fun by +writing your test functions in parallel with the "production +code", since this makes it easy to find bugs and even +design flaws earlier. +

+"Support modules" that are not intended to be the main +module of a program may include a "test script interpretation" +which invokes a self test of the module. +

+

+   if __name__ == "__main__":
+      self_test()
+
+Even programs that interact with complex external +interfaces may be tested when the external interfaces are +unavailable by using "fake" interfaces implemented in +Python. For an example of a "fake" interface, the following +class defines (part of) a "fake" file interface: +

+

+ import string
+ testdata = "just a random sequence of characters"
+
+
+ class FakeInputFile:
+   data = testdata
+   position = 0
+   closed = 0
+
+
+   def read(self, n=None):
+       self.testclosed()
+       p = self.position
+       if n is None:
+          result= self.data[p:]
+       else:
+          result= self.data[p: p+n]
+       self.position = p + len(result)
+       return result
+
+
+   def seek(self, n, m=0):
+       self.testclosed()
+       last = len(self.data)
+       p = self.position
+       if m==0: 
+          final=n
+       elif m==1:
+          final=n+p
+       elif m==2:
+          final=len(self.data)+n
+       else:
+          raise ValueError, "bad m"
+       if final<0:
+          raise IOError, "negative seek"
+       self.position = final
+
+
+   def isatty(self):
+       return 0
+
+
+   def tell(self):
+       return self.position
+
+
+   def close(self):
+       self.closed = 1
+
+
+   def testclosed(self):
+       if self.closed:
+          raise IOError, "file closed"
+
+Try f=FakeInputFile() and test out its operations. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:12:10 2002 by +Neal Norwitz +

+ +


+

4.50. My multidimensional list (array) is broken! What gives?

+You probably tried to make a multidimensional array like this. +

+

+   A = [[None] * 2] * 3
+
+This makes a list containing 3 references to the same list of length +two. Changes to one row will show in all rows, which is probably not +what you want. The following works much better: +

+

+   A = [None]*3
+   for i in range(3):
+        A[i] = [None] * 2
+
+This generates a list containing 3 different lists of length two. +

+If you feel weird, you can also do it in the following way: +

+

+   w, h = 2, 3
+   A = map(lambda i,w=w: [None] * w, range(h))
+
+For Python 2.0 the above can be spelled using a list comprehension: +

+

+   w,h = 2,3
+   A = [ [None]*w for i in range(h) ]
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:18:35 2000 by +Bjorn Pettersen +

+ +


+

4.51. I want to do a complicated sort: can you do a Schwartzian Transform in Python?

+Yes, and in Python you only have to write it once: +

+

+ def st(List, Metric):
+     def pairing(element, M = Metric):
+           return (M(element), element)
+     paired = map(pairing, List)
+     paired.sort()
+     return map(stripit, paired)
+
+
+ def stripit(pair):
+     return pair[1]
+
+This technique, attributed to Randal Schwartz, sorts the elements +of a list by a metric which maps each element to its "sort value". +For example, if L is a list of string then +

+

+   import string
+   Usorted = st(L, string.upper)
+
+
+   def intfield(s):
+         return string.atoi( string.strip(s[10:15] ) )
+
+
+   Isorted = st(L, intfield)
+
+Usorted gives the elements of L sorted as if they were upper +case, and Isorted gives the elements of L sorted by the integer +values that appear in the string slices starting at position 10 +and ending at position 15. In Python 2.0 this can be done more +naturally with list comprehensions: +

+

+  tmp1 = [ (x.upper(), x) for x in L ] # Schwartzian transform
+  tmp1.sort()
+  Usorted = [ x[1] for x in tmp1 ]
+
+
+  tmp2 = [ (int(s[10:15]), s) for s in L ] # Schwartzian transform
+  tmp2.sort()
+  Isorted = [ x[1] for x in tmp2 ]
+
+

+Note that Isorted may also be computed by +

+

+   def Icmp(s1, s2):
+         return cmp( intfield(s1), intfield(s2) )
+
+
+   Isorted = L[:]
+   Isorted.sort(Icmp)
+
+but since this method computes intfield many times for each +element of L, it is slower than the Schwartzian Transform. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Jun 1 19:18:46 2002 by +Neal Norwitz +

+ +


+

4.52. How to convert between tuples and lists?

+The function tuple(seq) converts any sequence into a tuple with +the same items in the same order. +For example, tuple([1, 2, 3]) yields (1, 2, 3) and tuple('abc') +yields ('a', 'b', 'c'). If the argument is +a tuple, it does not make a copy but returns the same object, so +it is cheap to call tuple() when you aren't sure that an object +is already a tuple. +

+The function list(seq) converts any sequence into a list with +the same items in the same order. +For example, list((1, 2, 3)) yields [1, 2, 3] and list('abc') +yields ['a', 'b', 'c']. If the argument is a list, +it makes a copy just like seq[:] would. +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 14 14:18:53 1998 by +Tim Peters +

+ +


+

4.53. Files retrieved with urllib contain leading garbage that looks like email headers.

+Extremely old versions of Python supplied libraries which +did not support HTTP/1.1; the vanilla httplib in Python 1.4 +only recognized HTTP/1.0. In Python 2.0 full HTTP/1.1 support is included. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 8 17:26:18 2001 by +Steve Holden +

+ +


+

4.54. How do I get a list of all instances of a given class?

+Python does not keep track of all instances of a class (or of a +built-in type). +

+You can program the class's constructor to keep track of all +instances, but unless you're very clever, this has the disadvantage +that the instances never get deleted,because your list of all +instances keeps a reference to them. +

+(The trick is to regularly inspect the reference counts of the +instances you've retained, and if the reference count is below a +certain level, remove it from the list. Determining that level is +tricky -- it's definitely larger than 1.) +

+ +Edit this entry / +Log info + +/ Last changed on Tue May 27 23:52:16 1997 by +GvR +

+ +


+

4.55. A regular expression fails with regex.error: match failure.

+This is usually caused by too much backtracking; the regular +expression engine has a fixed size stack which holds at most 4000 +backtrack points. Every character matched by e.g. ".*" accounts for a +backtrack point, so even a simple search like +

+

+  regex.match('.*x',"x"*5000)
+
+will fail. +

+This is fixed in the re module introduced with +Python 1.5; consult the Library Reference section on re for more information. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 30 12:35:49 1998 by +A.M. Kuchling +

+ +


+

4.56. I can't get signal handlers to work.

+The most common problem is that the signal handler is declared +with the wrong argument list. It is called as +

+

+	handler(signum, frame)
+
+so it should be declared with two arguments: +

+

+	def handler(signum, frame):
+		...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed May 28 09:29:08 1997 by +GvR +

+ +


+

4.57. I can't use a global variable in a function? Help!

+Did you do something like this? +

+

+   x = 1 # make a global
+
+
+   def f():
+         print x # try to print the global
+         ...
+         for j in range(100):
+              if q>3:
+                 x=4
+
+Any variable assigned in a function is local to that function. +unless it is specifically declared global. Since a value is bound +to x as the last statement of the function body, the compiler +assumes that x is local. Consequently the "print x" +attempts to print an uninitialized local variable and will +trigger a NameError. +

+In such cases the solution is to insert an explicit global +declaration at the start of the function, making it +

+

+

+   def f():
+         global x
+         print x # try to print the global
+         ...
+         for j in range(100):
+              if q>3:
+                 x=4
+
+

+In this case, all references to x are interpreted as references +to the x from the module namespace. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Feb 12 15:52:12 2001 by +Steve Holden +

+ +


+

4.58. What's a negative index? Why doesn't list.insert() use them?

+Python sequences are indexed with positive numbers and +negative numbers. For positive numbers 0 is the first index +1 is the second index and so forth. For negative indices -1 +is the last index and -2 is the pentultimate (next to last) index +and so forth. Think of seq[-n] as the same as seq[len(seq)-n]. +

+Using negative indices can be very convenient. For example +if the string Line ends in a newline then Line[:-1] is all of Line except +the newline. +

+Sadly the list builtin method L.insert does not observe negative +indices. This feature could be considered a mistake but since +existing programs depend on this feature it may stay around +forever. L.insert for negative indices inserts at the start of the +list. To get "proper" negative index behaviour use L[n:n] = [x] +in place of the insert method. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:03:18 1997 by +aaron watters +

+ +


+

4.59. How can I sort one list by values from another list?

+You can sort lists of tuples. +

+

+  >>> list1 = ["what", "I'm", "sorting", "by"]
+  >>> list2 = ["something", "else", "to", "sort"]
+  >>> pairs = map(None, list1, list2)
+  >>> pairs
+  [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
+  >>> pairs.sort()
+  >>> pairs
+  [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
+  >>> result = pairs[:]
+  >>> for i in xrange(len(result)): result[i] = result[i][1]
+  ...
+  >>> result
+  ['else', 'sort', 'to', 'something']
+
+And if you didn't understand the question, please see the +example above ;c). Note that "I'm" sorts before "by" because +uppercase "I" comes before lowercase "b" in the ascii order. +Also see 4.51. +

+In Python 2.0 this can be done like: +

+

+ >>> list1 = ["what", "I'm", "sorting", "by"]
+ >>> list2 = ["something", "else", "to", "sort"]
+ >>> pairs = zip(list1, list2)
+ >>> pairs
+ [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
+ >>> pairs.sort()
+ >>> result = [ x[1] for x in pairs ]
+ >>> result
+ ['else', 'sort', 'to', 'something']
+
+[Followup] +

+Someone asked, why not this for the last steps: +

+

+  result = []
+  for p in pairs: result.append(p[1])
+
+This is much more legible. However, a quick test shows that +it is almost twice as slow for long lists. Why? First of all, +the append() operation has to reallocate memory, and while it +uses some tricks to avoid doing that each time, it still has +to do it occasionally, and apparently that costs quite a bit. +Second, the expression "result.append" requires an extra +attribute lookup. The attribute lookup could be done away +with by rewriting as follows: +

+

+  result = []
+  append = result.append
+  for p in pairs: append(p[1])
+
+which gains back some speed, but is still considerably slower +than the original solution, and hardly less convoluted. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:56:35 2000 by +Bjorn Pettersen +

+ +


+

4.60. Why doesn't dir() work on builtin types like files and lists?

+It does starting with Python 1.5. +

+Using 1.4, you can find out which methods a given object supports +by looking at its __methods__ attribute: +

+

+    >>> List = []
+    >>> List.__methods__
+    ['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort']
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Sep 16 14:56:42 1999 by +Skip Montanaro +

+ +


+

4.61. How can I mimic CGI form submission (METHOD=POST)?

+I would like to retrieve web pages that are the result of POSTing a +form. Is there existing code that would let me do this easily? +

+Yes. Here's a simple example that uses httplib. +

+

+    #!/usr/local/bin/python
+
+
+    import httplib, sys, time
+
+
+    ### build the query string
+    qs = "First=Josephine&MI=Q&Last=Public"
+
+
+    ### connect and send the server a path
+    httpobj = httplib.HTTP('www.some-server.out-there', 80)
+    httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')
+    ### now generate the rest of the HTTP headers...
+    httpobj.putheader('Accept', '*/*')
+    httpobj.putheader('Connection', 'Keep-Alive')
+    httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
+    httpobj.putheader('Content-length', '%d' % len(qs))
+    httpobj.endheaders()
+    httpobj.send(qs)
+    ### find out what the server said in response...
+    reply, msg, hdrs = httpobj.getreply()
+    if reply != 200:
+	sys.stdout.write(httpobj.getfile().read())
+
+Note that in general for "url encoded posts" (the default) query strings must be "quoted" to, for example, change equals signs and spaces to an encoded form when they occur in name or value. Use urllib.quote to perform this quoting. For example to send name="Guy Steele, Jr.": +

+

+   >>> from urllib import quote
+   >>> x = quote("Guy Steele, Jr.")
+   >>> x
+   'Guy%20Steele,%20Jr.'
+   >>> query_string = "name="+x
+   >>> query_string
+   'name=Guy%20Steele,%20Jr.'
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 21 03:47:07 1999 by +TAB +

+ +


+

4.62. If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?

+Databases opened for write access with the bsddb module (and often by +the anydbm module, since it will preferentially use bsddb) must +explicitly be closed using the close method of the database. The +underlying libdb package caches database contents which need to be +converted to on-disk form and written, unlike regular open files which +already have the on-disk bits in the kernel's write buffer, where they +can just be dumped by the kernel with the program exits. +

+If you have initialized a new bsddb database but not written anything to +it before the program crashes, you will often wind up with a zero-length +file and encounter an exception the next time the file is opened. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:15:01 2002 by +Neal Norwitz +

+ +


+

4.63. How do I make a Python script executable on Unix?

+You need to do two things: the script file's mode must be executable +(include the 'x' bit), and the first line must begin with #! +followed by the pathname for the Python interpreter. +

+The first is done by executing 'chmod +x scriptfile' or perhaps +'chmod 755 scriptfile'. +

+The second can be done in a number of way. The most straightforward +way is to write +

+

+  #!/usr/local/bin/python
+
+as the very first line of your file - or whatever the pathname is +where the python interpreter is installed on your platform. +

+If you would like the script to be independent of where the python +interpreter lives, you can use the "env" program. On almost all +platforms, the following will work, assuming the python interpreter +is in a directory on the user's $PATH: +

+

+  #! /usr/bin/env python
+
+Note -- *don't* do this for CGI scripts. The $PATH variable for +CGI scripts is often very minimal, so you need to use the actual +absolute pathname of the interpreter. +

+Occasionally, a user's environment is so full that the /usr/bin/env +program fails; or there's no env program at all. +In that case, you can try the following hack (due to Alex Rezinsky): +

+

+  #! /bin/sh
+  """:"
+  exec python $0 ${1+"$@"}
+  """
+
+The disadvantage is that this defines the script's __doc__ string. +However, you can fix that by adding +

+

+  __doc__ = """...Whatever..."""
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 15 09:19:16 2001 by +Neal Norwitz +

+ +


+

4.64. How do you remove duplicates from a list?

+See the Python Cookbook for a long discussion of many cool ways: +

+

+    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
+
+Generally, if you don't mind reordering the List +

+

+   if List:
+      List.sort()
+      last = List[-1]
+      for i in range(len(List)-2, -1, -1):
+          if last==List[i]: del List[i]
+          else: last=List[i]
+
+If all elements of the list may be used as +dictionary keys (ie, they are all hashable) +this is often faster +

+

+   d = {}
+   for x in List: d[x]=x
+   List = d.values()
+
+Also, for extremely large lists you might +consider more optimal alternatives to the first one. +The second one is pretty good whenever it can +be used. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:56:33 2002 by +Tim Peters +

+ +


+

4.65. Are there any known year 2000 problems in Python?

+I am not aware of year 2000 deficiencies in Python 1.5. Python does +very few date calculations and for what it does, it relies on the C +library functions. Python generally represent times either as seconds +since 1970 or as a tuple (year, month, day, ...) where the year is +expressed with four digits, which makes Y2K bugs unlikely. So as long +as your C library is okay, Python should be okay. Of course, I cannot +vouch for your Python code! +

+Given the nature of freely available software, I have to add that this statement is not +legally binding. The Python copyright notice contains the following +disclaimer: +

+

+  STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
+  REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
+  MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
+  CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
+  DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
+  PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+  TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+  PERFORMANCE OF THIS SOFTWARE.
+
+The good news is that if you encounter a problem, you have full +source available to track it down and fix it! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 10 14:59:31 1998 by +GvR +

+ +


+

4.66. I want a version of map that applies a method to a sequence of objects! Help!

+Get fancy! +

+

+  def method_map(objects, method, arguments):
+       """method_map([a,b], "flog", (1,2)) gives [a.flog(1,2), b.flog(1,2)]"""
+       nobjects = len(objects)
+       methods = map(getattr, objects, [method]*nobjects)
+       return map(apply, methods, [arguments]*nobjects)
+
+It's generally a good idea to get to know the mysteries of map and apply +and getattr and the other dynamic features of Python. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 5 14:21:14 1998 by +Aaron Watters +

+ +


+

4.67. How do I generate random numbers in Python?

+The standard library module "random" implements a random number +generator. Usage is simple: +

+

+    import random
+
+
+    random.random()
+
+This returns a random floating point number in the range [0, 1). +

+There are also many other specialized generators in this module, such +as +

+

+    randrange(a, b) chooses an integer in the range [a, b)
+    uniform(a, b) chooses a floating point number in the range [a, b)
+    normalvariate(mean, sdev) sample from normal (Gaussian) distribution
+
+Some higher-level functions operate on sequences directly, such as +

+

+    choice(S) chooses random element from a given sequence
+    shuffle(L) shuffles a list in-place, i.e. permutes it randomly
+
+There's also a class, Random, which you can instantiate +to create independent multiple random number generators. +

+All this is documented in the library reference manual. Note that +the module "whrandom" is obsolete. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:16:51 2002 by +Neal Norwitz +

+ +


+

4.68. How do I access the serial (RS232) port?

+There's a Windows serial communication module (for communication +over RS 232 serial ports) at +

+

+  ftp://ftp.python.org/pub/python/contrib/sio-151.zip
+  http://www.python.org/ftp/python/contrib/sio-151.zip
+
+For DOS, try Hans Nowak's Python-DX, which supports this, at: +

+

+  http://www.cuci.nl/~hnowak/
+
+For Unix, see a usenet post by Mitch Chapman: +

+

+  http://groups.google.com/groups?selm=34A04430.CF9@ohioee.com
+
+For Win32, POSIX(Linux, BSD, *), Jython, Chris': +

+

+  http://pyserial.sourceforge.net
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jul 2 21:11:07 2002 by +Chris Liechti +

+ +


+

4.69. Images on Tk-Buttons don't work in Py15?

+They do work, but you must keep your own reference to the image +object now. More verbosely, you must make sure that, say, a global +variable or a class attribute refers to the object. +

+Quoting Fredrik Lundh from the mailinglist: +

+

+  Well, the Tk button widget keeps a reference to the internal
+  photoimage object, but Tkinter does not.  So when the last
+  Python reference goes away, Tkinter tells Tk to release the
+  photoimage.  But since the image is in use by a widget, Tk
+  doesn't destroy it.  Not completely.  It just blanks the image,
+  making it completely transparent...
+
+
+  And yes, there was a bug in the keyword argument handling
+  in 1.4 that kept an extra reference around in some cases.  And
+  when Guido fixed that bug in 1.5, he broke quite a few Tkinter
+  programs...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Feb 3 11:31:03 1998 by +Case Roole +

+ +


+

4.70. Where is the math.py (socket.py, regex.py, etc.) source file?

+If you can't find a source file for a module it may be a builtin +or dynamically loaded module implemented in C, C++ or other +compiled language. In this case you may not have the source +file or it may be something like mathmodule.c, somewhere in +a C source directory (not on the Python Path). +

+Fredrik Lundh (fredrik@pythonware.com) explains (on the python-list): +

+There are (at least) three kinds of modules in Python: +1) modules written in Python (.py); +2) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc); +3) modules written in C and linked with the interpreter; to get a list +of these, type: +

+

+    import sys
+    print sys.builtin_module_names
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Feb 3 13:55:33 1998 by +Aaron Watters +

+ +


+

4.71. How do I send mail from a Python script?

+The standard library module smtplib does this. +Here's a very simple interactive mail +sender that uses it. This method will work on any host that +supports an SMTP listener. +

+

+    import sys, smtplib
+
+
+    fromaddr = raw_input("From: ")
+    toaddrs  = raw_input("To: ").split(',')
+    print "Enter message, end with ^D:"
+    msg = ''
+    while 1:
+        line = sys.stdin.readline()
+        if not line:
+            break
+        msg = msg + line
+
+
+    # The actual mail send
+    server = smtplib.SMTP('localhost')
+    server.sendmail(fromaddr, toaddrs, msg)
+    server.quit()
+
+If the local host doesn't have an SMTP listener, you need to find one. The simple method is to ask the user. Alternately, you can use the DNS system to find the mail gateway(s) responsible for the source address. +

+A Unix-only alternative uses sendmail. The location of the +sendmail program varies between systems; sometimes it is +/usr/lib/sendmail, sometime /usr/sbin/sendmail. The sendmail manual +page will help you out. Here's some sample code: +

+

+  SENDMAIL = "/usr/sbin/sendmail" # sendmail location
+  import os
+  p = os.popen("%s -t -i" % SENDMAIL, "w")
+  p.write("To: cary@ratatosk.org\n")
+  p.write("Subject: test\n")
+  p.write("\n") # blank line separating headers from body
+  p.write("Some text\n")
+  p.write("some more text\n")
+  sts = p.close()
+  if sts != 0:
+      print "Sendmail exit status", sts
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 07:05:12 2002 by +Matthias Urlichs +

+ +


+

4.72. How do I avoid blocking in connect() of a socket?

+The select module is widely known to help with asynchronous +I/O on sockets once they are connected. However, it is less +than common knowledge how to avoid blocking on the initial +connect() call. Jeremy Hylton has the following advice (slightly +edited): +

+To prevent the TCP connect from blocking, you can set the socket to +non-blocking mode. Then when you do the connect(), you will either +connect immediately (unlikely) or get an exception that contains the +errno. errno.EINPROGRESS indicates that the connection is in +progress, but hasn't finished yet. Different OSes will return +different errnos, so you're going to have to check. I can tell you +that different versions of Solaris return different errno values. +

+In Python 1.5 and later, you can use connect_ex() to avoid +creating an exception. It will just return the errno value. +

+To poll, you can call connect_ex() again later -- 0 or errno.EISCONN +indicate that you're connected -- or you can pass this socket to +select (checking to see if it is writeable). +

+ +Edit this entry / +Log info + +/ Last changed on Tue Feb 24 21:30:45 1998 by +GvR +

+ +


+

4.73. How do I specify hexadecimal and octal integers?

+To specify an octal digit, precede the octal value with a zero. For example, +to set the variable "a" to the octal value "10" (8 in decimal), type: +

+

+    >>> a = 010
+
+To verify that this works, you can type "a" and hit enter while in the +interpreter, which will cause Python to spit out the current value of "a" +in decimal: +

+

+    >>> a
+    8
+
+Hexadecimal is just as easy. Simply precede the hexadecimal number with a +zero, and then a lower or uppercase "x". Hexadecimal digits can be specified +in lower or uppercase. For example, in the Python interpreter: +

+

+    >>> a = 0xa5
+    >>> a
+    165
+    >>> b = 0XB2
+    >>> b
+    178
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Mar 3 12:53:16 1998 by +GvR +

+ +


+

4.74. How to get a single keypress at a time?

+For Windows, see question 8.2. Here is an answer for Unix (see also 4.94). +

+There are several solutions; some involve using curses, which is a +pretty big thing to learn. Here's a solution without curses, due +to Andrew Kuchling (adapted from code to do a PGP-style +randomness pool): +

+

+        import termios, sys, os
+        fd = sys.stdin.fileno()
+        old = termios.tcgetattr(fd)
+        new = termios.tcgetattr(fd)
+        new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
+        new[6][termios.VMIN] = 1
+        new[6][termios.VTIME] = 0
+        termios.tcsetattr(fd, termios.TCSANOW, new)
+        s = ''    # We'll save the characters typed and add them to the pool.
+        try:
+            while 1:
+                c = os.read(fd, 1)
+                print "Got character", `c`
+                s = s+c
+        finally:
+            termios.tcsetattr(fd, termios.TCSAFLUSH, old)
+
+You need the termios module for any of this to work, and I've only +tried it on Linux, though it should work elsewhere. It turns off +stdin's echoing and disables canonical mode, and then reads a +character at a time from stdin, noting the time after each keystroke. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Oct 24 00:36:56 2002 by +chris +

+ +


+

4.75. How can I overload constructors (or methods) in Python?

+(This actually applies to all methods, but somehow the question +usually comes up first in the context of constructors.) +

+Where in C++ you'd write +

+

+    class C {
+        C() { cout << "No arguments\n"; }
+        C(int i) { cout << "Argument is " << i << "\n"; }
+    }
+
+in Python you have to write a single constructor that catches all +cases using default arguments. For example: +

+

+    class C:
+        def __init__(self, i=None):
+            if i is None:
+                print "No arguments"
+            else:
+                print "Argument is", i
+
+This is not entirely equivalent, but close enough in practice. +

+You could also try a variable-length argument list, e.g. +

+

+        def __init__(self, *args):
+            ....
+
+The same approach works for all method definitions. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 20 11:55:55 1998 by +GvR +

+ +


+

4.76. How do I pass keyword arguments from one method to another?

+Use apply. For example: +

+

+    class Account:
+        def __init__(self, **kw):
+            self.accountType = kw.get('accountType')
+            self.balance = kw.get('balance')
+
+
+    class CheckingAccount(Account):
+        def __init__(self, **kw):
+            kw['accountType'] = 'checking'
+            apply(Account.__init__, (self,), kw)
+
+
+    myAccount = CheckingAccount(balance=100.00)
+
+In Python 2.0 you can call it directly using the new ** syntax: +

+

+    class CheckingAccount(Account):
+        def __init__(self, **kw):
+            kw['accountType'] = 'checking'
+            Account.__init__(self, **kw)
+
+or more generally: +

+

+ >>> def f(x, *y, **z):
+ ...  print x,y,z
+ ...
+ >>> Y = [1,2,3]
+ >>> Z = {'foo':3,'bar':None}
+ >>> f('hello', *Y, **Z)
+ hello (1, 2, 3) {'foo': 3, 'bar': None}
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 13:04:01 2000 by +Bjorn Pettersen +

+ +


+

4.77. What module should I use to help with generating HTML?

+Check out HTMLgen written by Robin Friedrich. It's a class library +of objects corresponding to all the HTML 3.2 markup tags. It's used +when you are writing in Python and wish to synthesize HTML pages for +generating a web or for CGI forms, etc. +

+It can be found in the FTP contrib area on python.org or on the +Starship. Use the search engines there to locate the latest version. +

+It might also be useful to consider DocumentTemplate, which offers clear +separation between Python code and HTML code. DocumentTemplate is part +of the Bobo objects publishing system (http:/www.digicool.com/releases) +but can be used independantly of course! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 28 09:54:58 1998 by +GvR +

+ +


+

4.78. How do I create documentation from doc strings?

+Use gendoc, by Daniel Larson. See +

+http://starship.python.net/crew/danilo/ +

+It can create HTML from the doc strings in your Python source code. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Oct 7 17:15:51 2002 by +Phil Rittenhouse +

+ +


+

4.79. How do I read (or write) binary data?

+For complex data formats, it's best to use +use the struct module. It's documented in the library reference. +It allows you to take a string read from a file containing binary +data (usually numbers) and convert it to Python objects; and vice +versa. +

+For example, the following code reads two 2-byte integers +and one 4-byte integer in big-endian format from a file: +

+

+  import struct
+
+
+  f = open(filename, "rb")  # Open in binary mode for portability
+  s = f.read(8)
+  x, y, z = struct.unpack(">hhl", s)
+
+The '>' in the format string forces bin-endian data; the letter +'h' reads one "short integer" (2 bytes), and 'l' reads one +"long integer" (4 bytes) from the string. +

+For data that is more regular (e.g. a homogeneous list of ints or +floats), you can also use the array module, also documented +in the library reference. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Oct 7 09:16:45 1998 by +GvR +

+ +


+

4.80. I can't get key bindings to work in Tkinter

+An oft-heard complaint is that event handlers bound to events +with the bind() method don't get handled even when the appropriate +key is pressed. +

+The most common cause is that the widget to which the binding applies +doesn't have "keyboard focus". Check out the Tk documentation +for the focus command. Usually a widget is given the keyboard +focus by clicking in it (but not for labels; see the taketocus +option). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 12 09:37:33 1998 by +GvR +

+ +


+

4.81. "import crypt" fails

+[Unix] +

+Starting with Python 1.5, the crypt module is disabled by default. +In order to enable it, you must go into the Python source tree and +edit the file Modules/Setup to enable it (remove a '#' sign in +front of the line starting with '#crypt'). Then rebuild. +You may also have to add the string '-lcrypt' to that same line. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 5 08:57:09 1998 by +GvR +

+ +


+

4.82. Are there coding standards or a style guide for Python programs?

+Yes, Guido has written the "Python Style Guide". See +http://www.python.org/doc/essays/styleguide.html +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 29 09:50:27 1998 by +Joseph VanAndel +

+ +


+

4.83. How do I freeze Tkinter applications?

+Freeze is a tool to create stand-alone applications (see 4.28). +

+When freezing Tkinter applications, the applications will not be +truly stand-alone, as the application will still need the tcl and +tk libraries. +

+One solution is to ship the application with the tcl and tk libraries, +and point to them at run-time using the TCL_LIBRARY and TK_LIBRARY +environment variables. +

+To get truly stand-alone applications, the Tcl scripts that form +the library have to be integrated into the application as well. One +tool supporting that is SAM (stand-alone modules), which is part +of the Tix distribution (http://tix.mne.com). Build Tix with SAM +enabled, perform the appropriate call to Tclsam_init etc inside +Python's Modules/tkappinit.c, and link with libtclsam +and libtksam (you might include the Tix libraries as well). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jan 20 17:35:01 1999 by +Martin v. Löwis +

+ +


+

4.84. How do I create static class data and static class methods?

+[Tim Peters, tim_one@email.msn.com] +

+Static data (in the sense of C++ or Java) is easy; static methods (again in the sense of C++ or Java) are not supported directly. +

+STATIC DATA +

+For example, +

+

+    class C:
+        count = 0   # number of times C.__init__ called
+
+
+        def __init__(self):
+            C.count = C.count + 1
+
+
+        def getcount(self):
+            return C.count  # or return self.count
+
+c.count also refers to C.count for any c such that isinstance(c, C) holds, unless overridden by c itself or by some class on the base-class search path from c.__class__ back to C. +

+Caution: within a method of C, +

+

+    self.count = 42
+
+creates a new and unrelated instance vrbl named "count" in self's own dict. So rebinding of a class-static data name needs the +

+

+    C.count = 314
+
+form whether inside a method or not. +

+

+STATIC METHODS +

+Static methods (as opposed to static data) are unnatural in Python, because +

+

+    C.getcount
+
+returns an unbound method object, which can't be invoked without supplying an instance of C as the first argument. +

+The intended way to get the effect of a static method is via a module-level function: +

+

+    def getcount():
+        return C.count
+
+If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation. +

+Several tortured schemes for faking static methods can be found by searching DejaNews. Most people feel such cures are worse than the disease. Perhaps the least obnoxious is due to Pekka Pessi (mailto:ppessi@hut.fi): +

+

+    # helper class to disguise function objects
+    class _static:
+        def __init__(self, f):
+            self.__call__ = f
+
+
+    class C:
+        count = 0
+
+
+        def __init__(self):
+            C.count = C.count + 1
+
+
+        def getcount():
+            return C.count
+        getcount = _static(getcount)
+
+
+        def sum(x, y):
+            return x + y
+        sum = _static(sum)
+
+
+    C(); C()
+    c = C()
+    print C.getcount()  # prints 3
+    print c.getcount()  # prints 3
+    print C.sum(27, 15) # prints 42
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Jan 21 21:35:38 1999 by +Tim Peters +

+ +


+

4.85. __import__('x.y.z') returns <module 'x'>; how do I get z?

+Try +

+

+   __import__('x.y.z').y.z
+
+For more realistic situations, you may have to do something like +

+

+   m = __import__(s)
+   for i in string.split(s, ".")[1:]:
+       m = getattr(m, i)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Jan 28 11:01:43 1999 by +GvR +

+ +


+

4.86. Basic thread wisdom

+Please note that there is no way to take advantage of +multiprocessor hardware using the Python thread model. The interpreter +uses a global interpreter lock (GIL), +which does not allow multiple threads to be concurrently active. +

+If you write a simple test program like this: +

+

+  import thread
+  def run(name, n):
+      for i in range(n): print name, i
+  for i in range(10):
+      thread.start_new(run, (i, 100))
+
+none of the threads seem to run! The reason is that as soon as +the main thread exits, all threads are killed. +

+A simple fix is to add a sleep to the end of the program, +sufficiently long for all threads to finish: +

+

+  import thread, time
+  def run(name, n):
+      for i in range(n): print name, i
+  for i in range(10):
+      thread.start_new(run, (i, 100))
+  time.sleep(10) # <----------------------------!
+
+But now (on many platforms) the threads don't run in parallel, +but appear to run sequentially, one at a time! The reason is +that the OS thread scheduler doesn't start a new thread until +the previous thread is blocked. +

+A simple fix is to add a tiny sleep to the start of the run +function: +

+

+  import thread, time
+  def run(name, n):
+      time.sleep(0.001) # <---------------------!
+      for i in range(n): print name, i
+  for i in range(10):
+      thread.start_new(run, (i, 100))
+  time.sleep(10)
+
+Some more hints: +

+Instead of using a time.sleep() call at the end, it's +better to use some kind of semaphore mechanism. One idea is to +use a the Queue module to create a queue object, let each thread +append a token to the queue when it finishes, and let the main +thread read as many tokens from the queue as there are threads. +

+Use the threading module instead of the thread module. It's part +of Python since version 1.5.1. It takes care of all these details, +and has many other nice features too! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Feb 7 16:21:55 2003 by +GvR +

+ +


+

4.87. Why doesn't closing sys.stdout (stdin, stderr) really close it?

+Python file objects are a high-level layer of abstraction on top of C streams, which in turn are a medium-level layer of abstraction on top of (among other things) low-level C file descriptors. +

+For most file objects f you create in Python via the builtin "open" function, f.close() marks the Python file object as being closed from Python's point of view, and also arranges to close the underlying C stream. This happens automatically too, in f's destructor, when f becomes garbage. +

+But stdin, stdout and stderr are treated specially by Python, because of the special status also given to them by C: doing +

+

+    sys.stdout.close() # ditto for stdin and stderr
+
+marks the Python-level file object as being closed, but does not close the associated C stream (provided sys.stdout is still bound to its default value, which is the stream C also calls "stdout"). +

+To close the underlying C stream for one of these three, you should first be sure that's what you really want to do (e.g., you may confuse the heck out of extension modules trying to do I/O). If it is, use os.close: +

+

+    os.close(0)   # close C's stdin stream
+    os.close(1)   # close C's stdout stream
+    os.close(2)   # close C's stderr stream
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sat Apr 17 02:22:35 1999 by +Tim Peters +

+ +


+

4.88. What kinds of global value mutation are thread-safe?

+[adapted from c.l.py responses by Gordon McMillan & GvR] +

+A global interpreter lock (GIL) is used internally to ensure that only one thread runs in the Python VM at a time. In general, Python offers to switch among threads only between bytecode instructions (how frequently it offers to switch can be set via sys.setcheckinterval). Each bytecode instruction-- and all the C implementation code reached from it --is therefore atomic. +

+In theory, this means an exact accounting requires an exact understanding of the PVM bytecode implementation. In practice, it means that operations on shared vrbls of builtin data types (ints, lists, dicts, etc) that "look atomic" really are. +

+For example, these are atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y +are objects, i, j are ints): +

+

+    L.append(x)
+    L1.extend(L2)
+    x = L[i]
+    x = L.pop()
+    L1[i:j] = L2
+    L.sort()
+    x = y
+    x.field = y
+    D[x] = y
+    D1.update(D2)
+    D.keys()
+
+These aren't: +

+

+    i = i+1
+    L.append(L[-1])
+    L[i] = L[j]
+    D[x] = D[x] + 1
+
+Note: operations that replace other objects may invoke those other objects' __del__ method when their reference count reaches zero, and that can affect things. This is especially true for the mass updates to dictionaries and lists. When in doubt, use a mutex! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Feb 7 16:21:03 2003 by +GvR +

+ +


+

4.89. How do I modify a string in place?

+Strings are immutable (see question 6.2) so you cannot modify a string +directly. If you need an object with this ability, try converting the +string to a list or take a look at the array module. +

+

+    >>> s = "Hello, world"
+    >>> a = list(s)
+    >>> print a
+    ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
+    >>> a[7:] = list("there!")
+    >>> import string
+    >>> print string.join(a, '')
+    'Hello, there!'
+
+
+    >>> import array
+    >>> a = array.array('c', s)
+    >>> print a
+    array('c', 'Hello, world')
+    >>> a[0] = 'y' ; print a
+    array('c', 'yello world')
+    >>> a.tostring()
+    'yello, world'
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue May 18 01:22:47 1999 by +Andrew Dalke +

+ +


+

4.90. How to pass on keyword/optional parameters/arguments

+Q: How can I pass on optional or keyword parameters from one function to another? +

+

+	def f1(a, *b, **c):
+		...
+
+A: In Python 2.0 and above: +

+

+	def f2(x, *y, **z):
+		...
+		z['width']='14.3c'
+		...
+		f1(x, *y, **z)
+
+
+   Note: y can be any sequence (e.g., list or tuple) and z must be a dict.
+
+

+A: For versions prior to 2.0, use 'apply', like: +

+

+	def f2(x, *y, **z):
+		...
+		z['width']='14.3c'
+		...
+		apply(f1, (x,)+y, z)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 07:20:56 2002 by +Matthias Urlichs +

+ +


+

4.91. How can I get a dictionary to display its keys in a consistent order?

+In general, dictionaries store their keys in an unpredictable order, +so the display order of a dictionary's elements will be similarly +unpredictable. +(See +Question 6.12 +to understand why this is so.) +

+This can be frustrating if you want to save a printable version to a +file, make some changes and then compare it with some other printed +dictionary. If you have such needs you can subclass UserDict.UserDict +to create a SortedDict class that prints itself in a predictable order. +Here's one simpleminded implementation of such a class: +

+

+  import UserDict, string
+
+
+  class SortedDict(UserDict.UserDict):
+    def __repr__(self):
+      result = []
+      append = result.append
+      keys = self.data.keys()
+      keys.sort()
+      for k in keys:
+        append("%s: %s" % (`k`, `self.data[k]`))
+      return "{%s}" % string.join(result, ", ")
+
+
+    ___str__ = __repr__
+
+

+This will work for many common situations you might encounter, though +it's far from a perfect solution. (It won't have any effect on the +pprint module and does not transparently handle values that are or +contain dictionaries. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Sep 16 17:31:06 1999 by +Skip Montanaro +

+ +


+

4.92. Is there a Python tutorial?

+Yes. See question 1.20 at +http://www.python.org/doc/FAQ.html#1.20 +

+ +Edit this entry / +Log info + +/ Last changed on Sat Dec 4 16:04:00 1999 by +TAB +

+ +


+

4.93. Deleted

+See 4.28 +

+ +Edit this entry / +Log info + +/ Last changed on Tue May 28 20:40:37 2002 by +GvR +

+ +


+

4.94. How do I get a single keypress without blocking?

+There are several solutions; some involve using curses, which is a +pretty big thing to learn. Here's a solution without curses. (see also 4.74, for Windows, see question 8.2) +

+

+  import termios, fcntl, sys, os
+  fd = sys.stdin.fileno()
+
+
+  oldterm = termios.tcgetattr(fd)
+  newattr = termios.tcgetattr(fd)
+  newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
+  termios.tcsetattr(fd, termios.TCSANOW, newattr)
+
+
+  oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
+  fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
+
+
+  try:
+      while 1:
+          try:
+              c = sys.stdin.read(1)
+              print "Got character", `c`
+          except IOError: pass
+  finally:
+      termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
+      fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
+
+

+You need the termios and the fcntl module for any of this to work, +and I've only tried it on Linux, though it should work elsewhere. +

+In this code, characters are read and printed one at a time. +

+termios.tcsetattr() turns off stdin's echoing and disables canonical +mode. fcntl.fnctl() is used to obtain stdin's file descriptor flags +and modify them for non-blocking mode. Since reading stdin when it is +empty results in an IOError, this error is caught and ignored. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Oct 24 00:39:06 2002 by +chris +

+ +


+

4.95. Is there an equivalent to Perl chomp()? (Remove trailing newline from string)

+There are two partial substitutes. If you want to remove all trailing +whitespace, use the method string.rstrip(). Otherwise, if there is only +one line in the string, use string.splitlines()[0]. +

+

+ -----------------------------------------------------------------------
+
+
+ rstrip() is too greedy, it strips all trailing white spaces.
+ splitlines() takes ControlM as line boundary.
+ Consider these strings as input:
+   "python python    \r\n"
+   "python\rpython\r\n"
+   "python python   \r\r\r\n"
+ The results from rstrip()/splitlines() are perhaps not what we want.
+
+
+ It seems re can perform this task.
+
+

+

+ #!/usr/bin/python 
+ # requires python2                                                             
+
+
+ import re, os, StringIO
+
+
+ lines=StringIO.StringIO(
+   "The Python Programming Language\r\n"
+   "The Python Programming Language \r \r \r\r\n"
+   "The\rProgramming\rLanguage\r\n"
+   "The\rProgramming\rLanguage\r\r\r\r\n"
+   "The\r\rProgramming\r\rLanguage\r\r\r\r\n"
+ )
+
+
+ ln=re.compile("(?:[\r]?\n|\r)$") # dos:\r\n, unix:\n, mac:\r, others: unknown
+ # os.linesep does not work if someone ftps(in binary mode) a dos/mac text file
+ # to your unix box
+ #ln=re.compile(os.linesep + "$")
+
+
+ while 1:
+   s=lines.readline()
+   if not s: break
+   print "1.(%s)" % `s.rstrip()`
+   print "2.(%s)" % `ln.sub( "", s, 1)`
+   print "3.(%s)" % `s.splitlines()[0]`
+   print "4.(%s)" % `s.splitlines()`
+   print
+
+
+ lines.close()
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 8 09:51:34 2001 by +Crystal +

+ +


+

4.96. Why is join() a string method when I'm really joining the elements of a (list, tuple, sequence)?

+Strings became much more like other standard types starting in release 1.6, when methods were added which give the same functionality that has always been available using the functions of the string module. These new methods have been widely accepted, but the one which appears to make (some) programmers feel uncomfortable is: +

+

+    ", ".join(['1', '2', '4', '8', '16'])
+
+which gives the result +

+

+    "1, 2, 4, 8, 16"
+
+There are two usual arguments against this usage. +

+The first runs along the lines of: "It looks really ugly using a method of a string literal (string constant)", to which the answer is that it might, but a string literal is just a fixed value. If the methods are to be allowed on names bound to strings there is no logical reason to make them unavailable on literals. Get over it! +

+The second objection is typically cast as: "I am really telling a sequence to join its members together with a string constant". Sadly, you aren't. For some reason there seems to be much less difficulty with having split() as a string method, since in that case it is easy to see that +

+

+    "1, 2, 4, 8, 16".split(", ")
+
+is an instruction to a string literal to return the substrings delimited by the given separator (or, by default, arbitrary runs of white space). In this case a Unicode string returns a list of Unicode strings, an ASCII string returns a list of ASCII strings, and everyone is happy. +

+join() is a string method because in using it you are telling the separator string to iterate over an arbitrary sequence, forming string representations of each of the elements, and inserting itself between the elements' representations. This method can be used with any argument which obeys the rules for sequence objects, inluding any new classes you might define yourself. +

+Because this is a string method it can work for Unicode strings as well as plain ASCII strings. If join() were a method of the sequence types then the sequence types would have to decide which type of string to return depending on the type of the separator. +

+If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write +

+

+    string.join(['1', '2', '4', '8', '16'], ", ")
+
+You will just have to try and forget that the string module actually uses the syntax you are compaining about to implement the syntax you prefer! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 2 15:51:58 2002 by +Steve Holden +

+ +


+

4.97. How can my code discover the name of an object?

+Generally speaking, it can't, because objects don't really have names. The assignment statement does not store the assigned value in the name but a reference to it. Essentially, assignment creates a binding of a name to a value. The same is true of def and class statements, but in that case the value is a callable. Consider the following code: +

+

+    class A:
+        pass
+
+
+    B = A
+
+
+    a = B()
+    b = a
+    print b
+    <__main__.A instance at 016D07CC>
+    print a
+    <__main__.A instance at 016D07CC>
+
+

+Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value. +

+Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 8 03:53:39 2001 by +Steve Holden +

+ +


+

4.98. Why are floating point calculations so inaccurate?

+The development version of the Python Tutorial now contains an Appendix with more info: +
+    http://www.python.org/doc/current/tut/node14.html
+
+People are often very surprised by results like this: +

+

+ >>> 1.2-1.0
+ 0.199999999999999996
+
+And think it is a bug in Python. It's not. It's a problem caused by +the internal representation of a floating point number. A floating point +number is stored as a fixed number of binary digits. +

+In decimal math, there are many numbers that can't be represented +with a fixed number of decimal digits, i.e. +1/3 = 0.3333333333....... +

+In the binary case, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc. There are +a lot of numbers that can't be represented. The digits are cut off at +some point. +

+Since Python 1.6, a floating point's repr() function prints as many +digits are necessary to make eval(repr(f)) == f true for any float f. +The str() function prints the more sensible number that was probably +intended: +

+

+ >>> 0.2
+ 0.20000000000000001
+ >>> print 0.2
+ 0.2
+
+Again, this has nothing to do with Python, but with the way the +underlying C platform handles floating points, and ultimately with +the inaccuracy you'll always have when writing down numbers of fixed +number of digit strings. +

+One of the consequences of this is that it is dangerous to compare +the result of some computation to a float with == ! +Tiny inaccuracies may mean that == fails. +

+Instead try something like this: +

+

+ epsilon = 0.0000000000001 # Tiny allowed error
+ expected_result = 0.4
+
+
+ if expected_result-epsilon <= computation() <= expected_result+epsilon:
+    ...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 1 22:18:47 2002 by +Fred Drake +

+ +


+

4.99. I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?

+Don't panic! Your data are probably intact. The most frequent cause +for the error is that you tried to open an earlier Berkeley DB file +with a later version of the Berkeley DB library. +

+Many Linux systems now have all three versions of Berkeley DB +available. If you are migrating from version 1 to a newer version use +db_dump185 to dump a plain text version of the database. +If you are migrating from version 2 to version 3 use db2_dump to create +a plain text version of the database. In either case, use db_load to +create a new native database for the latest version installed on your +computer. If you have version 3 of Berkeley DB installed, you should +be able to use db2_load to create a native version 2 database. +

+You should probably move away from Berkeley DB version 1 files because +the hash file code contains known bugs that can corrupt your data. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 29 16:04:29 2001 by +Skip Montanaro +

+ +


+

4.100. What are the "best practices" for using import in a module?

+First, the standard modules are great. Use them! The standard Python library is large and varied. Using modules can save you time and effort and will reduce maintainenance cost of your code. (Other programs are dedicated to supporting and fixing bugs in the standard Python modules. Coworkers may also be familiar with themodules that you use, reducing the amount of time it takes them to understand your code.) +

+The rest of this answer is largely a matter of personal preference, but here's what some newsgroup posters said (thanks to all who responded) +

+In general, don't use +

+ from modulename import *
+
+Doing so clutters the importer's namespace. Some avoid this idiom even with the few modules that were designed to be imported in this manner. (Modules designed in this manner include Tkinter, thread, and wxPython.) +

+Import modules at the top of a file, one module per line. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports. +

+Move imports into a local scope (such as at the top of a function definition) if there are a lot of imports, and you're trying to avoid the cost (lots of initialization time) of many imports. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive (because of the one time initialization of the module) but that loading a module multiple times is virtually free (a couple of dictionary lookups). Even if the module name has gone out of scope, the module is probably available in sys.modules. Thus, there isn't really anything wrong with putting no imports at the module level (if they aren't needed) and putting all of the imports at the function level. +

+It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon says: +

+ Circular imports are fine where both modules use the "import <module>"
+ form of import. They fail when the 2nd module wants to grab a name
+ out of the first ("from module import name") and the import is at
+ the top level. That's because names in the 1st are not yet available,
+ (the first module is busy importing the 2nd).  
+
+In this case, if the 2nd module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import. +

+It may also be necessary to move imports out of the top level of code +if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option. +

+If only instances of a specific class uses a module, then it is reasonable to import the module in the class's __init__ method and then assign the module to an instance variable so that the module is always available (via that instance variable) during the life of the object. Note that to delay an import until the class is instantiated, the import must be inside a method. Putting the import inside the class but outside of any method still causes the import to occur when the module is initialized. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Aug 4 04:44:47 2001 by +TAB +

+ +


+

4.101. Is there a tool to help find bugs or perform static analysis?

+Yes. PyChecker is a static analysis tool for finding bugs +in Python source code as well as warning about code complexity +and style. +

+You can get PyChecker from: http://pychecker.sf.net. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 10 15:42:11 2001 by +Neal +

+ +


+

4.102. UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)

+This error indicates that your Python installation can handle +only 7-bit ASCII strings. There are a couple ways to fix or +workaround the problem. +

+If your programs must handle data in arbitary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. You need to convert the input to Unicode data using that encoding. For instance, a program that handles email or web input will typically find character set encoding information in Content-Type headers. This can then be used to properly convert input data to Unicode. Assuming the string referred to by "value" is encoded as UTF-8: +

+

+    value = unicode(value, "utf-8")
+
+will return a Unicode object. If the data is not correctly encoded as UTF-8, the above call will raise a UnicodeError. +

+If you only want strings coverted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails: +

+

+    try:
+        x = unicode(value, "ascii")
+    except UnicodeError:
+        value = unicode(value, "utf-8")
+    else:
+        # value was valid ASCII data
+        pass
+
+

+If you normally use a character set encoding other than US-ASCII and only need to handle data in that encoding, the simplest way to fix the problem may be simply to set the encoding in sitecustomize.py. The following code is just a modified version of the encoding setup code from site.py with the relevant lines uncommented. +

+

+    # Set the string encoding used by the Unicode implementation.
+    # The default is 'ascii'
+    encoding = "ascii" # <= CHANGE THIS if you wish
+
+
+    # Enable to support locale aware default string encodings.
+    import locale
+    loc = locale.getdefaultlocale()
+    if loc[1]:
+        encoding = loc[1]
+    if encoding != "ascii":
+        import sys
+        sys.setdefaultencoding(encoding)
+
+

+Also note that on Windows, there is an encoding known as "mbcs", which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Apr 13 04:45:41 2002 by +Skip Montanaro +

+ +


+

4.103. Using strings to call functions/methods

+There are various techniques: +

+* Use a dictionary pre-loaded with strings and functions. The primary +advantage of this technique is that the strings do not need to match the +names of the functions. This is also the primary technique used to +emulate a case construct: +

+

+    def a():
+        pass
+
+
+    def b():
+        pass
+
+
+    dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs
+
+
+    dispatch[get_input()]()  # Note trailing parens to call function
+
+* Use the built-in function getattr(): +

+

+    import foo
+    getattr(foo, 'bar')()
+
+Note that getattr() works on any object, including classes, class +instances, modules, and so on. +

+This is used in several places in the standard library, like +this: +

+

+    class Foo:
+        def do_foo(self):
+            ...
+
+
+        def do_bar(self):
+            ...
+
+
+     f = getattr(foo_instance, 'do_' + opname)
+     f()
+
+

+* Use locals() or eval() to resolve the function name: +

+def myFunc(): +

+    print "hello"
+
+fname = "myFunc" +

+f = locals()[fname] +f() +

+f = eval(fname) +f() +

+Note: Using eval() can be dangerous. If you don't have absolute control +over the contents of the string, all sorts of things could happen... +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 08:14:58 2002 by +Erno Kuusela +

+ +


+

4.104. How fast are exceptions?

+A try/except block is extremely efficient. Actually executing an +exception is expensive. In older versions of Python (prior to 2.0), it +was common to code this idiom: +

+

+    try:
+        value = dict[key]
+    except KeyError:
+        dict[key] = getvalue(key)
+        value = dict[key]
+
+This idiom only made sense when you expected the dict to have the key +95% of the time or more; other times, you coded it like this: +

+

+    if dict.has_key(key):
+        value = dict[key]
+    else:
+        dict[key] = getvalue(key)
+        value = dict[key]
+
+In Python 2.0 and higher, of course, you can code this as +

+

+    value = dict.setdefault(key, getvalue(key))
+
+However this evaluates getvalue(key) always, regardless of whether it's needed or not. So if it's slow or has a side effect you should use one of the above variants. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 9 10:12:30 2002 by +Yeti +

+ +


+

4.105. Sharing global variables across modules

+The canonical way to share information across modules within a single +program is to create a special module (often called config or cfg). +Just import the config module in all modules of your application; the +module then becomes available as a global name. Because there is only +one instance of each module, any changes made to the module object get +reflected everywhere. For example: +

+config.py: +

+

+    pass
+
+mod.py: +

+

+    import config
+    config.x = 1
+
+main.py: +

+

+    import config
+    import mod
+    print config.x
+
+Note that using a module is also the basis for implementing the +Singleton design pattern, for the same reason. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Apr 23 23:07:19 2002 by +Aahz +

+ +


+

4.106. Why is cPickle so slow?

+Use the binary option. We'd like to make that the default, but it would +break backward compatibility: +

+

+    largeString = 'z' * (100 * 1024)
+    myPickle = cPickle.dumps(largeString, 1)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Aug 22 19:54:25 2002 by +Aahz +

+ +


+

4.107. When importing module XXX, why do I get "undefined symbol: PyUnicodeUCS2_..." ?

+You are using a version of Python that uses a 4-byte representation for +Unicode characters, but the extension module you are importing (possibly +indirectly) was compiled using a Python that uses a 2-byte representation +for Unicode characters (the default). +

+If instead the name of the undefined symbol starts with PyUnicodeUCS4_, +the problem is the same by the relationship is reversed: Python was +built using 2-byte Unicode characters, and the extension module was +compiled using a Python with 4-byte Unicode characters. +

+This can easily occur when using pre-built extension packages. RedHat +Linux 7.x, in particular, provides a "python2" binary that is compiled +with 4-byte Unicode. This only causes the link failure if the extension +uses any of the PyUnicode_*() functions. It is also a problem if if an +extension uses any of the Unicode-related format specifiers for +Py_BuildValue (or similar) or parameter-specifications for +PyArg_ParseTuple(). +

+You can check the size of the Unicode character a Python interpreter is +using by checking the value of sys.maxunicode: +

+

+  >>> import sys
+  >>> if sys.maxunicode > 65535:
+  ...     print 'UCS4 build'
+  ... else:
+  ...     print 'UCS2 build'
+
+The only way to solve this problem is to use extension modules compiled +with a Python binary built using the same size for Unicode characters. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Aug 27 15:00:17 2002 by +Fred Drake +

+ +


+

4.108. How do I create a .pyc file?

+QUESTION: +

+I have a module and I wish to generate a .pyc file. +How do I do it? Everything I read says that generation of a .pyc file is +"automatic", but I'm not getting anywhere. +

+

+ANSWER: +

+When a module is imported for the first time (or when the source is more +recent than the current compiled file) a .pyc file containing the compiled code should be created in the +same directory as the .py file. +

+One reason that a .pyc file may not be created is permissions problems with the directory. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server. +

+However, in most cases, that's not the problem. +

+Creation of a .pyc file is "automatic" if you are importing a module and Python has the +ability (permissions, free space, etc...) to write the compiled module +back to the directory. But note that running Python on a top level script is not considered an +import and so no .pyc will be created automatically. For example, if you have a top-level module abc.py that imports another module xyz.py, when you run abc, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc isn't imported. +

+If you need to create abc.pyc -- that is, to create a .pyc file for a +module that is not imported -- you can. (Look up +the py_compile and compileall modules in the Library Reference.) +

+You can manually compile any module using the "py_compile" module. One +way is to use the compile() function in that module interactively: +

+

+    >>> import py_compile
+    >>> py_compile.compile('abc.py')
+
+This will write the .pyc to the same location as abc.py (or you +can override that with the optional parameter cfile). +

+You can also automatically compile all files in a directory or +directories using the "compileall" module, which can also be run +straight from the command line. +

+You can do it from the shell (or DOS) prompt by entering: +

+       python compile.py abc.py
+
+or +
+       python compile.py *
+
+Or you can write a script to do it on a list of filenames that you enter. +

+

+     import sys
+     from py_compile import compile
+
+
+     if len(sys.argv) <= 1:
+        sys.exit(1)
+
+
+     for file in sys.argv[1:]:
+        compile(file)
+
+ACKNOWLEDGMENTS: +

+Steve Holden, David Bolen, Rich Somerfield, Oleg Broytmann, Steve Ferg +

+ +Edit this entry / +Log info + +/ Last changed on Wed Feb 12 15:58:25 2003 by +Stephen Ferg +

+ +


+

5. Extending Python

+ +
+

5.1. Can I create my own functions in C?

+Yes, you can create built-in modules containing functions, +variables, exceptions and even new types in C. This is explained in +the document "Extending and Embedding the Python Interpreter" (http://www.python.org/doc/current/ext/ext.html). Also read the chapter +on dynamic loading. +

+There's more information on this in each of the Python books: +Programming Python, Internet Programming with Python, and Das Python-Buch +(in German). +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 10 05:18:57 2001 by +Fred L. Drake, Jr. +

+ +


+

5.2. Can I create my own functions in C++?

+Yes, using the C-compatibility features found in C++. Basically +you place extern "C" { ... } around the Python include files and put +extern "C" before each function that is going to be called by the +Python interpreter. Global or static C++ objects with constructors +are probably not a good idea. +

+ +Edit this entry / +Log info +

+ +


+

5.3. How can I execute arbitrary Python statements from C?

+The highest-level function to do this is PyRun_SimpleString() which takes +a single string argument which is executed in the context of module +__main__ and returns 0 for success and -1 when an exception occurred +(including SyntaxError). If you want more control, use PyRun_String(); +see the source for PyRun_SimpleString() in Python/pythonrun.c. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 20:08:14 1997 by +Bill Tutt +

+ +


+

5.4. How can I evaluate an arbitrary Python expression from C?

+Call the function PyRun_String() from the previous question with the +start symbol eval_input (Py_eval_input starting with 1.5a1); it +parses an expression, evaluates it and returns its value. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 22:23:18 1997 by +David Ascher +

+ +


+

5.5. How do I extract C values from a Python object?

+That depends on the object's type. If it's a tuple, +PyTupleSize(o) returns its length and PyTuple_GetItem(o, i) +returns its i'th item; similar for lists with PyListSize(o) +and PyList_GetItem(o, i). For strings, PyString_Size(o) returns +its length and PyString_AsString(o) a pointer to its value +(note that Python strings may contain null bytes so strlen() +is not safe). To test which type an object is, first make sure +it isn't NULL, and then use PyString_Check(o), PyTuple_Check(o), +PyList_Check(o), etc. +

+There is also a high-level API to Python objects which is +provided by the so-called 'abstract' interface -- read +Include/abstract.h for further details. It allows for example +interfacing with any kind of Python sequence (e.g. lists and tuples) +using calls like PySequence_Length(), PySequence_GetItem(), etc.) +as well as many other useful protocols. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 22:34:20 1997 by +David Ascher +

+ +


+

5.6. How do I use Py_BuildValue() to create a tuple of arbitrary length?

+You can't. Use t = PyTuple_New(n) instead, and fill it with +objects using PyTuple_SetItem(t, i, o) -- note that this "eats" a +reference count of o. Similar for lists with PyList_New(n) and +PyList_SetItem(l, i, o). Note that you must set all the tuple items to +some value before you pass the tuple to Python code -- +PyTuple_New(n) initializes them to NULL, which isn't a valid Python +value. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 31 18:15:29 1997 by +Guido van Rossum +

+ +


+

5.7. How do I call an object's method from C?

+The PyObject_CallMethod() function can be used to call an arbitrary +method of an object. The parameters are the object, the name of the +method to call, a format string like that used with Py_BuildValue(), and the argument values: +

+

+    PyObject *
+    PyObject_CallMethod(PyObject *object, char *method_name,
+                        char *arg_format, ...);
+
+This works for any object that has methods -- whether built-in or +user-defined. You are responsible for eventually DECREF'ing the +return value. +

+To call, e.g., a file object's "seek" method with arguments 10, 0 +(assuming the file object pointer is "f"): +

+

+        res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
+        if (res == NULL) {
+                ... an exception occurred ...
+        }
+        else {
+                Py_DECREF(res);
+        }
+
+Note that since PyObject_CallObject() always wants a tuple for the +argument list, to call a function without arguments, pass "()" for the +format, and to call a function with one argument, surround the argument +in parentheses, e.g. "(i)". +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 6 16:15:46 2002 by +Neal Norwitz +

+ +


+

5.8. How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?

+(Due to Mark Hammond): +

+In Python code, define an object that supports the "write()" method. +Redirect sys.stdout and sys.stderr to this object. +Call print_error, or just allow the standard traceback mechanism to +work. Then, the output will go wherever your write() method sends it. +

+The easiest way to do this is to use the StringIO class in the standard +library. +

+Sample code and use for catching stdout: +

+	>>> class StdoutCatcher:
+	...  def __init__(self):
+	...   self.data = ''
+	...  def write(self, stuff):
+	...   self.data = self.data + stuff
+	...  
+	>>> import sys
+	>>> sys.stdout = StdoutCatcher()
+	>>> print 'foo'
+	>>> print 'hello world!'
+	>>> sys.stderr.write(sys.stdout.data)
+	foo
+	hello world!
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Dec 16 18:34:25 1998 by +Richard Jones +

+ +


+

5.9. How do I access a module written in Python from C?

+You can get a pointer to the module object as follows: +

+

+        module = PyImport_ImportModule("<modulename>");
+
+If the module hasn't been imported yet (i.e. it is not yet present in +sys.modules), this initializes the module; otherwise it simply returns +the value of sys.modules["<modulename>"]. Note that it doesn't enter +the module into any namespace -- it only ensures it has been +initialized and is stored in sys.modules. +

+You can then access the module's attributes (i.e. any name defined in +the module) as follows: +

+

+        attr = PyObject_GetAttrString(module, "<attrname>");
+
+Calling PyObject_SetAttrString(), to assign to variables in the module, also works. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 22:56:40 1997 by +david ascher +

+ +


+

5.10. How do I interface to C++ objects from Python?

+Depending on your requirements, there are many approaches. To do +this manually, begin by reading the "Extending and Embedding" document +(Doc/ext.tex, see also http://www.python.org/doc/). Realize +that for the Python run-time system, there isn't a whole lot of +difference between C and C++ -- so the strategy to build a new Python +type around a C structure (pointer) type will also work for C++ +objects. +

+A useful automated approach (which also works for C) is SWIG: +http://www.swig.org/. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Oct 15 05:14:01 1999 by +Sjoerd Mullender +

+ +


+

5.11. mSQLmodule (or other old module) won't build with Python 1.5 (or later)

+Since python-1.4 "Python.h" will have the file includes needed in an +extension module. +Backward compatibility is dropped after version 1.4 and therefore +mSQLmodule.c will not build as "allobjects.h" cannot be found. +The following change in mSQLmodule.c is harmless when building it with +1.4 and necessary when doing so for later python versions: +

+Remove lines: +

+

+	#include "allobjects.h"
+	#include "modsupport.h"
+
+And insert instead: +

+

+	#include "Python.h"
+
+You may also need to add +

+

+                #include "rename2.h"
+
+if the module uses "old names". +

+This may happen with other ancient python modules as well, +and the same fix applies. +

+ +Edit this entry / +Log info + +/ Last changed on Sun Dec 21 02:03:35 1997 by +GvR +

+ +


+

5.12. I added a module using the Setup file and the make fails! Huh?

+Setup must end in a newline, if there is no newline there it gets +very sad. Aside from this possibility, maybe you have other +non-Python-specific linkage problems. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jun 24 15:54:01 1997 by +aaron watters +

+ +


+

5.13. I want to compile a Python module on my Red Hat Linux system, but some files are missing.

+Red Hat's RPM for Python doesn't include the +/usr/lib/python1.x/config/ directory, which contains various files required +for compiling Python extensions. +Install the python-devel RPM to get the necessary files. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 26 13:44:04 1999 by +A.M. Kuchling +

+ +


+

5.14. What does "SystemError: _PyImport_FixupExtension: module yourmodule not loaded" mean?

+This means that you have created an extension module named "yourmodule", but your module init function does not initialize with that name. +

+Every module init function will have a line similar to: +

+

+  module = Py_InitModule("yourmodule", yourmodule_functions);
+
+If the string passed to this function is not the same name as your extenion module, the SystemError will be raised. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 25 07:16:08 1999 by +Mark Hammond +

+ +


+

5.15. How to tell "incomplete input" from "invalid input"?

+Sometimes you want to emulate the Python interactive interpreter's +behavior, where it gives you a continuation prompt when the input +is incomplete (e.g. you typed the start of an "if" statement +or you didn't close your parentheses or triple string quotes), +but it gives you a syntax error message immediately when the input +is invalid. +

+In Python you can use the codeop module, which approximates the +parser's behavior sufficiently. IDLE uses this, for example. +

+The easiest way to do it in C is to call PyRun_InteractiveLoop() +(in a separate thread maybe) and let the Python interpreter handle +the input for you. You can also set the PyOS_ReadlineFunctionPointer +to point at your custom input function. See Modules/readline.c and +Parser/myreadline.c for more hints. +

+However sometimes you have to run the embedded Python interpreter +in the same thread as your rest application and you can't allow the +PyRun_InteractiveLoop() to stop while waiting for user input. +The one solution then is to call PyParser_ParseString() +and test for e.error equal to E_EOF (then the input is incomplete). +Sample code fragment, untested, inspired by code from Alex Farber: +

+

+  #include <Python.h>
+  #include <node.h>
+  #include <errcode.h>
+  #include <grammar.h>
+  #include <parsetok.h>
+  #include <compile.h>
+
+
+  int testcomplete(char *code)
+    /* code should end in \n */
+    /* return -1 for error, 0 for incomplete, 1 for complete */
+  {
+    node *n;
+    perrdetail e;
+
+
+    n = PyParser_ParseString(code, &_PyParser_Grammar,
+                             Py_file_input, &e);
+    if (n == NULL) {
+      if (e.error == E_EOF) 
+        return 0;
+      return -1;
+    }
+
+
+    PyNode_Free(n);
+    return 1;
+  }
+
+Another solution is trying to compile the received string with +Py_CompileString(). If it compiles fine - try to execute the returned +code object by calling PyEval_EvalCode(). Otherwise save the input for +later. If the compilation fails, find out if it's an error or just +more input is required - by extracting the message string from the +exception tuple and comparing it to the "unexpected EOF while parsing". +Here is a complete example using the GNU readline library (you may +want to ignore SIGINT while calling readline()): +

+

+  #include <stdio.h>
+  #include <readline.h>
+
+
+  #include <Python.h>
+  #include <object.h>
+  #include <compile.h>
+  #include <eval.h>
+
+
+  int main (int argc, char* argv[])
+  {
+    int i, j, done = 0;                          /* lengths of line, code */
+    char ps1[] = ">>> ";
+    char ps2[] = "... ";
+    char *prompt = ps1;
+    char *msg, *line, *code = NULL;
+    PyObject *src, *glb, *loc;
+    PyObject *exc, *val, *trb, *obj, *dum;
+
+
+    Py_Initialize ();
+    loc = PyDict_New ();
+    glb = PyDict_New ();
+    PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());
+
+
+    while (!done)
+    {
+      line = readline (prompt);
+
+
+      if (NULL == line)                          /* CTRL-D pressed */
+      {
+        done = 1;
+      }
+      else
+      {
+        i = strlen (line);
+
+
+        if (i > 0)
+          add_history (line);                    /* save non-empty lines */
+
+
+        if (NULL == code)                        /* nothing in code yet */
+          j = 0;
+        else
+          j = strlen (code);
+
+
+        code = realloc (code, i + j + 2);
+        if (NULL == code)                        /* out of memory */
+          exit (1);
+
+
+        if (0 == j)                              /* code was empty, so */
+          code[0] = '\0';                        /* keep strncat happy */
+
+
+        strncat (code, line, i);                 /* append line to code */
+        code[i + j] = '\n';                      /* append '\n' to code */
+        code[i + j + 1] = '\0';
+
+
+        src = Py_CompileString (code, "<stdin>", Py_single_input);       
+
+
+        if (NULL != src)                         /* compiled just fine - */
+        {
+          if (ps1  == prompt ||                  /* ">>> " or */
+              '\n' == code[i + j - 1])           /* "... " and double '\n' */
+          {                                               /* so execute it */
+            dum = PyEval_EvalCode ((PyCodeObject *)src, glb, loc);
+            Py_XDECREF (dum);
+            Py_XDECREF (src);
+            free (code);
+            code = NULL;
+            if (PyErr_Occurred ())
+              PyErr_Print ();
+            prompt = ps1;
+          }
+        }                                        /* syntax error or E_EOF? */
+        else if (PyErr_ExceptionMatches (PyExc_SyntaxError))           
+        {
+          PyErr_Fetch (&exc, &val, &trb);        /* clears exception! */
+
+
+          if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
+              !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
+          {
+            Py_XDECREF (exc);
+            Py_XDECREF (val);
+            Py_XDECREF (trb);
+            prompt = ps2;
+          }
+          else                                   /* some other syntax error */
+          {
+            PyErr_Restore (exc, val, trb);
+            PyErr_Print ();
+            free (code);
+            code = NULL;
+            prompt = ps1;
+          }
+        }
+        else                                     /* some non-syntax error */
+        {
+          PyErr_Print ();
+          free (code);
+          code = NULL;
+          prompt = ps1;
+        }
+
+
+        free (line);
+      }
+    }
+
+
+    Py_XDECREF(glb);
+    Py_XDECREF(loc);
+    Py_Finalize();
+    exit(0);
+  }
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Mar 15 09:47:24 2000 by +Alex Farber +

+ +


+

5.16. How do I debug an extension?

+When using gdb with dynamically loaded extensions, you can't set a +breakpoint in your extension until your extension is loaded. +

+In your .gdbinit file (or interactively), add the command +

+br _PyImport_LoadDynamicModule +

+

+$ gdb /local/bin/python +

+gdb) run myscript.py +

+gdb) continue # repeat until your extension is loaded +

+gdb) finish # so that your extension is loaded +

+gdb) br myfunction.c:50 +

+gdb) continue +

+ +Edit this entry / +Log info + +/ Last changed on Fri Oct 20 11:10:32 2000 by +Joe VanAndel +

+ +


+

5.17. How do I find undefined Linux g++ symbols, __builtin_new or __pure_virtural

+To dynamically load g++ extension modules, you must recompile python, relink python using g++ (change LINKCC in the python Modules Makefile), and link your extension module using g++ (e.g., "g++ -shared -o mymodule.so mymodule.o"). +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jan 14 18:03:51 2001 by +douglas orr +

+ +


+

5.18. How do I define and create objects corresponding to built-in/extension types

+Usually you would like to be able to inherit from a Python type when +you ask this question. The bottom line for Python 2.2 is: types and classes are miscible. You build instances by calling classes, and you can build subclasses to your heart's desire. +

+You need to be careful when instantiating immutable types like integers or strings. See http://www.amk.ca/python/2.2/, section 2, for details. +

+Prior to version 2.2, Python (like Java) insisted that there are first-class and second-class objects (the former are types, the latter classes), and never the twain shall meet. +

+The library has, however, done a good job of providing class wrappers for the more commonly desired objects (see UserDict, UserList and UserString for examples), and more are always welcome if you happen to be in the mood to write code. These wrappers still exist in Python 2.2. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 10 15:14:07 2002 by +Matthias Urlichs +

+ +


+

6. Python's design

+ +
+

6.1. Why isn't there a switch or case statement in Python?

+You can do this easily enough with a sequence of +if... elif... elif... else. There have been some proposals for switch +statement syntax, but there is no consensus (yet) on whether and how +to do range tests. +

+ +Edit this entry / +Log info +

+ +


+

6.2. Why does Python use indentation for grouping of statements?

+Basically I believe that using indentation for grouping is +extremely elegant and contributes a lot to the clarity of the average +Python program. Most people learn to love this feature after a while. +Some arguments for it: +

+Since there are no begin/end brackets there cannot be a disagreement +between grouping perceived by the parser and the human reader. I +remember long ago seeing a C fragment like this: +

+

+        if (x <= y)
+                x++;
+                y--;
+        z++;
+
+and staring a long time at it wondering why y was being decremented +even for x > y... (And I wasn't a C newbie then either.) +

+Since there are no begin/end brackets, Python is much less prone to +coding-style conflicts. In C there are loads of different ways to +place the braces (including the choice whether to place braces around +single statements in certain cases, for consistency). If you're used +to reading (and writing) code that uses one style, you will feel at +least slightly uneasy when reading (or being required to write) +another style. +Many coding styles place begin/end brackets on a line by themself. +This makes programs considerably longer and wastes valuable screen +space, making it harder to get a good overview over a program. +Ideally, a function should fit on one basic tty screen (say, 20 +lines). 20 lines of Python are worth a LOT more than 20 lines of C. +This is not solely due to the lack of begin/end brackets (the lack of +declarations also helps, and the powerful operations of course), but +it certainly helps! +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 16:00:15 1997 by +GvR +

+ +


+

6.3. Why are Python strings immutable?

+There are two advantages. One is performance: knowing that a +string is immutable makes it easy to lay it out at construction time +-- fixed and unchanging storage requirements. (This is also one of +the reasons for the distinction between tuples and lists.) The +other is that strings in Python are considered as "elemental" as +numbers. No amount of activity will change the value 8 to anything +else, and in Python, no amount of activity will change the string +"eight" to anything else. (Adapted from Jim Roskind) +

+ +Edit this entry / +Log info +

+ +


+

6.4. Delete

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 03:05:25 2001 by +Moshe Zadka +

+ +


+

6.5. Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?

+The major reason is history. Functions were used for those +operations that were generic for a group of types and which +were intended to work even for objects that didn't have +methods at all (e.g. numbers before type/class unification +began, or tuples). +

+It is also convenient to have a function that can readily be applied +to an amorphous collection of objects when you use the functional features of Python (map(), apply() et al). +

+In fact, implementing len(), max(), min() as a built-in function is +actually less code than implementing them as methods for each type. +One can quibble about individual cases but it's a part of Python, +and it's too late to change such things fundamentally now. The +functions have to remain to avoid massive code breakage. +

+Note that for string operations Python has moved from external functions +(the string module) to methods. However, len() is still a function. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 30 14:08:58 2002 by +Steve Holden +

+ +


+

6.6. Why can't I derive a class from built-in types (e.g. lists or files)?

+As of Python 2.2, you can derive from built-in types. For previous versions, the answer is: +

+This is caused by the relatively late addition of (user-defined) +classes to the language -- the implementation framework doesn't easily +allow it. See the answer to question 4.2 for a work-around. This +may be fixed in the (distant) future. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 23 02:53:22 2002 by +Neal Norwitz +

+ +


+

6.7. Why must 'self' be declared and used explicitly in method definitions and calls?

+So, is your current programming language C++ or Java? :-) +When classes were added to Python, this was (again) the simplest way of +implementing methods without too many changes to the interpreter. The +idea was borrowed from Modula-3. It turns out to be very useful, for +a variety of reasons. +

+First, it makes it more obvious that you are using a method or +instance attribute instead of a local variable. Reading "self.x" or +"self.meth()" makes it absolutely clear that an instance variable or +method is used even if you don't know the class definition by heart. +In C++, you can sort of tell by the lack of a local variable +declaration (assuming globals are rare or easily recognizable) -- but +in Python, there are no local variable declarations, so you'd have to +look up the class definition to be sure. +

+Second, it means that no special syntax is necessary if you want to +explicitly reference or call the method from a particular class. In +C++, if you want to use a method from base class that is overridden in +a derived class, you have to use the :: operator -- in Python you can +write baseclass.methodname(self, <argument list>). This is +particularly useful for __init__() methods, and in general in cases +where a derived class method wants to extend the base class method of +the same name and thus has to call the base class method somehow. +

+Lastly, for instance variables, it solves a syntactic problem with +assignment: since local variables in Python are (by definition!) those +variables to which a value assigned in a function body (and that +aren't explicitly declared global), there has to be some way to tell +the interpreter that an assignment was meant to assign to an instance +variable instead of to a local variable, and it should preferably be +syntactic (for efficiency reasons). C++ does this through +declarations, but Python doesn't have declarations and it would be a +pity having to introduce them just for this purpose. Using the +explicit "self.var" solves this nicely. Similarly, for using instance +variables, having to write "self.var" means that references to +unqualified names inside a method don't have to search the instance's +directories. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jan 12 08:01:50 2001 by +Steve Holden +

+ +


+

6.8. Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?

+Answer 1: Unfortunately, the interpreter pushes at least one C stack +frame for each Python stack frame. Also, extensions can call back into +Python at almost random moments. Therefore a complete threads +implementation requires thread support for C. +

+Answer 2: Fortunately, there is Stackless Python, which has a completely redesigned interpreter loop that avoids the C stack. It's still experimental but looks very promising. Although it is binary compatible with standard Python, it's still unclear whether Stackless will make it into the core -- maybe it's just too revolutionary. Stackless Python currently lives here: http://www.stackless.com. A microthread implementation that uses it can be found here: http://world.std.com/~wware/uthread.html. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Apr 15 08:18:16 2000 by +Just van Rossum +

+ +


+

6.9. Why can't lambda forms contain statements?

+Python lambda forms cannot contain statements because Python's +syntactic framework can't handle statements nested inside expressions. +

+However, in Python, this is not a serious problem. Unlike lambda +forms in other languages, where they add functionality, Python lambdas +are only a shorthand notation if you're too lazy to define a function. +

+Functions are already first class objects in Python, and can be +declared in a local scope. Therefore the only advantage of using a +lambda form instead of a locally-defined function is that you don't need to invent a name for the function -- but that's just a local variable to which the function object (which is exactly the same type of object that a lambda form yields) is assigned! +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 14 14:15:17 1998 by +Tim Peters +

+ +


+

6.10. [deleted]

+[lambda vs non-nested scopes used to be here] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:20:56 2002 by +Erno Kuusela +

+ +


+

6.11. [deleted]

+[recursive functions vs non-nested scopes used to be here] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:22:04 2002 by +Erno Kuusela +

+ +


+

6.12. Why is there no more efficient way of iterating over a dictionary than first constructing the list of keys()?

+As of Python 2.2, you can now iterate over a dictionary directly, +using the new implied dictionary iterator: +

+

+    for k in d: ...
+
+There are also methods returning iterators over the values and items: +

+

+    for k in d.iterkeys(): # same as above
+    for v in d.itervalues(): # iterate over values
+    for k, v in d.iteritems(): # iterate over items
+
+All these require that you do not modify the dictionary during the loop. +

+For previous Python versions, the following defense should do: +

+Have you tried it? I bet it's fast enough for your purposes! In +most cases such a list takes only a few percent of the space occupied +by the dictionary. Apart from the fixed header, +the list needs only 4 bytes (the size of a pointer) per +key. A dictionary uses 12 bytes per key plus between 30 and 70 +percent hash table overhead, plus the space for the keys and values. +By necessity, all keys are distinct objects, and a string object (the most +common key type) costs at least 20 bytes plus the length of the +string. Add to that the values contained in the dictionary, and you +see that 4 bytes more per item really isn't that much more memory... +

+A call to dict.keys() makes one fast scan over the dictionary +(internally, the iteration function does exist) copying the pointers +to the key objects into a pre-allocated list object of the right size. +The iteration time isn't lost (since you'll have to iterate anyway -- +unless in the majority of cases your loop terminates very prematurely +(which I doubt since you're getting the keys in random order). +

+I don't expose the dictionary iteration operation to Python +programmers because the dictionary shouldn't be modified during the +entire iteration -- if it is, there's a small chance that the +dictionary is reorganized because the hash table becomes too full, and +then the iteration may miss some items and see others twice. Exactly +because this only occurs rarely, it would lead to hidden bugs in +programs: it's easy never to have it happen during test runs if you +only insert or delete a few items per iteration -- but your users will +surely hit upon it sooner or later. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:24:08 2002 by +GvR +

+ +


+

6.13. Can Python be compiled to machine code, C or some other language?

+Not easily. Python's high level data types, dynamic typing of +objects and run-time invocation of the interpreter (using eval() or +exec) together mean that a "compiled" Python program would probably +consist mostly of calls into the Python run-time system, even for +seemingly simple operations like "x+1". +

+Several projects described in the Python newsgroup or at past +Python conferences have shown that this approach is feasible, +although the speedups reached so far are only modest (e.g. 2x). +JPython uses the same strategy for compiling to Java bytecode. +(Jim Hugunin has demonstrated that in combination with whole-program +analysis, speedups of 1000x are feasible for small demo programs. +See the website for the 1997 Python conference.) +

+Internally, Python source code is always translated into a "virtual +machine code" or "byte code" representation before it is interpreted +(by the "Python virtual machine" or "bytecode interpreter"). In order +to avoid the overhead of parsing and translating modules that rarely +change over and over again, this byte code is written on a file whose +name ends in ".pyc" whenever a module is parsed (from a file whose +name ends in ".py"). When the corresponding .py file is changed, it +is parsed and translated again and the .pyc file is rewritten. +

+There is no performance difference once the .pyc file has been loaded +(the bytecode read from the .pyc file is exactly the same as the bytecode +created by direct translation). The only difference is that loading +code from a .pyc file is faster than parsing and translating a .py +file, so the presence of precompiled .pyc files will generally improve +start-up time of Python scripts. If desired, the Lib/compileall.py +module/script can be used to force creation of valid .pyc files for a +given set of modules. +

+Note that the main script executed by Python, even if its filename +ends in .py, is not compiled to a .pyc file. It is compiled to +bytecode, but the bytecode is not saved to a file. +

+If you are looking for a way to translate Python programs in order to +distribute them in binary form, without the need to distribute the +interpreter and library as well, have a look at the freeze.py script +in the Tools/freeze directory. This creates a single binary file +incorporating your program, the Python interpreter, and those parts of +the Python library that are needed by your program. Of course, the +resulting binary will only run on the same type of platform as that +used to create it. +

+Newsflash: there are now several programs that do this, to some extent. +Look for Psyco, Pyrex, PyInline, Py2Cmod, and Weave. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:26:19 2002 by +GvR +

+ +


+

6.14. How does Python manage memory?

+The details of Python memory management depend on the implementation. +The standard Python implementation (the C implementation) uses reference +counting and another mechanism to collect reference cycles. +

+Jython relies on the Java runtime; so it uses +the JVM's garbage collector. This difference can cause some subtle +porting problems if your Python code depends on the behavior of +the reference counting implementation. +

+The reference cycle collector was added in CPython 2.0. It +periodically executes a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. A new gc module provides functions to perform a garbage collection, obtain debugging statistics, and tuning the collector's parameters. +

+The detection of cycles can be disabled when Python is compiled, if you can't afford even a tiny speed penalty or suspect that the cycle collection is buggy, by specifying the "--without-cycle-gc" switch when running the configure script. +

+Sometimes objects get stuck in "tracebacks" temporarily and hence are not deallocated when you might expect. Clear the tracebacks via +

+

+       import sys
+       sys.exc_traceback = sys.last_traceback = None
+
+Tracebacks are used for reporting errors and implementing debuggers and related things. They contain a portion of the program state extracted during the handling of an exception (usually the most recent exception). +

+In the absence of circularities and modulo tracebacks, Python programs need not explicitly manage memory. +

+Why python doesn't use a more traditional garbage collection +scheme? For one thing, unless this were +added to C as a standard feature, it's a portability pain in the ass. +And yes, I know about the Xerox library. It has bits of assembler +code for most common platforms. Not for all. And although it is +mostly transparent, it isn't completely transparent (when I once +linked Python with it, it dumped core). +

+Traditional GC also becomes a problem when Python gets embedded into +other applications. While in a stand-alone Python it may be fine to +replace the standard malloc() and free() with versions provided by the +GC library, an application embedding Python may want to have its own +substitute for malloc() and free(), and may not want Python's. Right +now, Python works with anything that implements malloc() and free() +properly. +

+In Jython, the following code (which is +fine in C Python) will probably run out of file descriptors long before +it runs out of memory: +

+

+        for file in <very long list of files>:
+                f = open(file)
+                c = f.read(1)
+
+Using the current reference counting and destructor scheme, each new +assignment to f closes the previous file. Using GC, this is not +guaranteed. Sure, you can think of ways to fix this. But it's not +off-the-shelf technology. If you want to write code that will +work with any Python implementation, you should explicitly close +the file; this will work regardless of GC: +

+

+       for file in <very long list of files>:
+                f = open(file)
+                c = f.read(1)
+                f.close()
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:35:38 2002 by +Erno Kuusela +

+ +


+

6.15. Why are there separate tuple and list data types?

+This is done so that tuples can be immutable while lists are mutable. +

+Immutable tuples are useful in situations where you need to pass a few +items to a function and don't want the function to modify the tuple; +for example, +

+

+	point1 = (120, 140)
+	point2 = (200, 300)
+	record(point1, point2)
+	draw(point1, point2)
+
+You don't want to have to think about what would happen if record() +changed the coordinates -- it can't, because the tuples are immutable. +

+On the other hand, when creating large lists dynamically, it is +absolutely crucial that they are mutable -- adding elements to a tuple +one by one requires using the concatenation operator, which makes it +quadratic in time. +

+As a general guideline, use tuples like you would use structs in C or +records in Pascal, use lists like (variable length) arrays. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 15:26:03 1997 by +GvR +

+ +


+

6.16. How are lists implemented?

+Despite what a Lisper might think, Python's lists are really +variable-length arrays. The implementation uses a contiguous +array of references to other objects, and keeps a pointer +to this array (as well as its length) in a list head structure. +

+This makes indexing a list (a[i]) an operation whose cost is +independent of the size of the list or the value of the index. +

+When items are appended or inserted, the array of references is resized. +Some cleverness is applied to improve the performance of appending +items repeatedly; when the array must be grown, some extra space +is allocated so the next few times don't require an actual resize. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 15:32:24 1997 by +GvR +

+ +


+

6.17. How are dictionaries implemented?

+Python's dictionaries are implemented as resizable hash tables. +

+Compared to B-trees, this gives better performance for lookup +(the most common operation by far) under most circumstances, +and the implementation is simpler. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 23:51:14 1997 by +Vladimir Marangozov +

+ +


+

6.18. Why must dictionary keys be immutable?

+The hash table implementation of dictionaries uses a hash value +calculated from the key value to find the key. If the key were +a mutable object, its value could change, and thus its hash could +change. But since whoever changes the key object can't tell that +is incorporated in a dictionary, it can't move the entry around in +the dictionary. Then, when you try to look up the same object +in the dictionary, it won't be found, since its hash value is different; +and if you try to look up the old value, it won't be found either, +since the value of the object found in that hash bin differs. +

+If you think you need to have a dictionary indexed with a list, +try to use a tuple instead. The function tuple(l) creates a tuple +with the same entries as the list l. +

+Some unacceptable solutions that have been proposed: +

+- Hash lists by their address (object ID). This doesn't work because +if you construct a new list with the same value it won't be found; +e.g., +

+

+  d = {[1,2]: '12'}
+  print d[[1,2]]
+
+will raise a KeyError exception because the id of the [1,2] used +in the second line differs from that in the first line. +In other words, dictionary keys should be compared using '==', not using 'is'. +

+- Make a copy when using a list as a key. This doesn't work because +the list (being a mutable object) could contain a reference to itself, +and then the copying code would run into an infinite loop. +

+- Allow lists as keys but tell the user not to modify them. This would +allow a class of hard-to-track bugs in programs that I'd rather not see; +it invalidates an important invariant of dictionaries (every value in +d.keys() is usable as a key of the dictionary). +

+- Mark lists as read-only once they are used as a dictionary key. +The problem is that it's not just the top-level object that could change +its value; you could use a tuple containing a list as a key. Entering +anything as a key into a dictionary would require marking all objects +reachable from there as read-only -- and again, self-referential objects +could cause an infinite loop again (and again and again). +

+There is a trick to get around this if you need to, but +use it at your own risk: You +can wrap a mutable structure inside a class instance which +has both a __cmp__ and a __hash__ method. +

+

+   class listwrapper:
+        def __init__(self, the_list):
+              self.the_list = the_list
+        def __cmp__(self, other):
+              return self.the_list == other.the_list
+        def __hash__(self):
+              l = self.the_list
+              result = 98767 - len(l)*555
+              for i in range(len(l)):
+                   try:
+                        result = result + (hash(l[i]) % 9999999) * 1001 + i
+                   except:
+                        result = (result % 7777777) + i * 333
+              return result
+
+Note that the hash computation is complicated by the +possibility that some members of the list may be unhashable +and also by the possibility of arithmetic overflow. +

+You must make +sure that the hash value for all such wrapper objects that reside in a +dictionary (or other hash based structure), remain fixed while +the object is in the dictionary (or other structure). +

+Furthermore it must always be the case that if +o1 == o2 (ie o1.__cmp__(o2)==0) then hash(o1)==hash(o2) +(ie, o1.__hash__() == o2.__hash__()), regardless of whether +the object is in a dictionary or not. +If you fail to meet these restrictions dictionaries and other +hash based structures may misbehave! +

+In the case of listwrapper above whenever the wrapper +object is in a dictionary the wrapped list must not change +to avoid anomalies. Don't do this unless you are prepared +to think hard about the requirements and the consequences +of not meeting them correctly. You've been warned! +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 10 10:08:40 1997 by +aaron watters +

+ +


+

6.19. How the heck do you make an array in Python?

+["this", 1, "is", "an", "array"] +

+Lists are arrays in the C or Pascal sense of the word (see question +6.16). The array module also provides methods for creating arrays +of fixed types with compact representations (but they are slower to +index than lists). Also note that the Numerics extensions and others +define array-like structures with various characteristics as well. +

+To get Lisp-like lists, emulate cons cells +

+

+    lisp_list = ("like",  ("this",  ("example", None) ) )
+
+using tuples (or lists, if you want mutability). Here the analogue +of lisp car is lisp_list[0] and the analogue of cdr is lisp_list[1]. +Only do this if you're sure you really need to (it's usually a lot +slower than using Python lists). +

+Think of Python lists as mutable heterogeneous arrays of +Python objects (say that 10 times fast :) ). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:08:27 1997 by +aaron watters +

+ +


+

6.20. Why doesn't list.sort() return the sorted list?

+In situations where performance matters, making a copy of the list +just to sort it would be wasteful. Therefore, list.sort() sorts +the list in place. In order to remind you of that fact, it does +not return the sorted list. This way, you won't be fooled into +accidentally overwriting a list when you need a sorted copy but also +need to keep the unsorted version around. +

+As a result, here's the idiom to iterate over the keys of a dictionary +in sorted order: +

+

+	keys = dict.keys()
+	keys.sort()
+	for key in keys:
+		...do whatever with dict[key]...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 2 17:01:52 1999 by +Fred L. Drake, Jr. +

+ +


+

6.21. How do you specify and enforce an interface spec in Python?

+An interfaces specification for a module as provided +by languages such as C++ and java describes the prototypes +for the methods and functions of the module. Many feel +that compile time enforcement of interface specifications +help aid in the construction of large programs. Python +does not support interface specifications directly, but many +of their advantages can be obtained by an appropriate +test discipline for components, which can often be very +easily accomplished in Python. There is also a tool, PyChecker, +which can be used to find problems due to subclassing. +

+A good test suite for a module can at +once provide a regression test and serve as a module interface +specification (even better since it also gives example usage). Look to +many of the standard libraries which often have a "script +interpretation" which provides a simple "self test." Even +modules which use complex external interfaces can often +be tested in isolation using trivial "stub" emulations of the +external interface. +

+An appropriate testing discipline (if enforced) can help +build large complex applications in Python as well as having interface +specifications would do (or better). Of course Python allows you +to get sloppy and not do it. Also you might want to design +your code with an eye to make it easily tested. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 23 03:05:29 2002 by +Neal Norwitz +

+ +


+

6.22. Why do all classes have the same type? Why do instances all have the same type?

+The Pythonic use of the word "type" is quite different from +common usage in much of the rest of the programming language +world. A "type" in Python is a description for an object's operations +as implemented in C. All classes have the same operations +implemented in C which sometimes "call back" to differing program +fragments implemented in Python, and hence all classes have the +same type. Similarly at the C level all class instances have the +same C implementation, and hence all instances have the same +type. +

+Remember that in Python usage "type" refers to a C implementation +of an object. To distinguish among instances of different classes +use Instance.__class__, and also look to 4.47. Sorry for the +terminological confusion, but at this point in Python's development +nothing can be done! +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jul 1 12:35:47 1997 by +aaron watters +

+ +


+

6.23. Why isn't all memory freed when Python exits?

+Objects referenced from Python module global name spaces are +not always deallocated when Python exits. +

+This may happen if there are circular references (see question +4.17). There are also certain bits of memory that are allocated +by the C library that are impossible to free (e.g. a tool +like Purify will complain about these). +

+But in general, Python 1.5 and beyond +(in contrast with earlier versions) is quite agressive about +cleaning up memory on exit. +

+If you want to force Python to delete certain things on deallocation +use the sys.exitfunc hook to force those deletions. For example +if you are debugging an extension module using a memory analysis +tool and you wish to make Python deallocate almost everything +you might use an exitfunc like this one: +

+

+  import sys
+
+
+  def my_exitfunc():
+       print "cleaning up"
+       import sys
+       # do order dependant deletions here
+       ...
+       # now delete everything else in arbitrary order
+       for x in sys.modules.values():
+            d = x.__dict__
+            for name in d.keys():
+                 del d[name]
+
+
+  sys.exitfunc = my_exitfunc
+
+Other exitfuncs can be less drastic, of course. +

+(In fact, this one just does what Python now already does itself; +but the example of using sys.exitfunc to force cleanups is still +useful.) +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 29 09:46:26 1998 by +GvR +

+ +


+

6.24. Why no class methods or mutable class variables?

+The notation +

+

+    instance.attribute(arg1, arg2)
+
+usually translates to the equivalent of +

+

+    Class.attribute(instance, arg1, arg2)
+
+where Class is a (super)class of instance. Similarly +

+

+    instance.attribute = value
+
+sets an attribute of an instance (overriding any attribute of a class +that instance inherits). +

+Sometimes programmers want to have +different behaviours -- they want a method which does not bind +to the instance and a class attribute which changes in place. +Python does not preclude these behaviours, but you have to +adopt a convention to implement them. One way to accomplish +this is to use "list wrappers" and global functions. +

+

+   def C_hello():
+         print "hello"
+
+
+   class C:
+        hello = [C_hello]
+        counter = [0]
+
+
+    I = C()
+
+Here I.hello[0]() acts very much like a "class method" and +I.counter[0] = 2 alters C.counter (and doesn't override it). +If you don't understand why you'd ever want to do this, that's +because you are pure of mind, and you probably never will +want to do it! This is dangerous trickery, not recommended +when avoidable. (Inspired by Tim Peter's discussion.) +

+In Python 2.2, you can do this using the new built-in operations +classmethod and staticmethod. +See http://www.python.org/2.2/descrintro.html#staticmethods +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 11 15:59:37 2001 by +GvR +

+ +


+

6.25. Why are default values sometimes shared between objects?

+It is often expected that a function CALL creates new objects for default +values. This is not what happens. Default values are created when the +function is DEFINED, that is, there is only one such object that all +functions refer to. If that object is changed, subsequent calls to the +function will refer to this changed object. By definition, immutable objects +(like numbers, strings, tuples, None) are safe from change. Changes to mutable +objects (like dictionaries, lists, class instances) is what causes the +confusion. +

+Because of this feature it is good programming practice not to use mutable +objects as default values, but to introduce them in the function. +Don't write: +

+

+	def foo(dict={}):  # XXX shared reference to one dict for all calls
+	    ...
+
+but: +
+	def foo(dict=None):
+		if dict is None:
+			dict = {} # create a new dict for local namespace
+
+See page 182 of "Internet Programming with Python" for one discussion +of this feature. Or see the top of page 144 or bottom of page 277 in +"Programming Python" for another discussion. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Aug 16 07:03:35 1997 by +Case Roole +

+ +


+

6.26. Why no goto?

+Actually, you can use exceptions to provide a "structured goto" +that even works across function calls. Many feel that exceptions +can conveniently emulate all reasonable uses of the "go" or "goto" +constructs of C, Fortran, and other languages. For example: +

+

+   class label: pass # declare a label
+   try:
+        ...
+        if (condition): raise label() # goto label
+        ...
+   except label: # where to goto
+        pass
+   ...
+
+This doesn't allow you to jump into the middle of a loop, but +that's usually considered an abuse of goto anyway. Use sparingly. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Sep 10 07:16:44 1997 by +aaron watters +

+ +


+

6.27. How do you make a higher order function in Python?

+You have two choices: you can use default arguments and override +them or you can use "callable objects." For example suppose you +wanted to define linear(a,b) which returns a function f where f(x) +computes the value a*x+b. Using default arguments: +

+

+     def linear(a,b):
+         def result(x, a=a, b=b):
+             return a*x + b
+         return result
+
+Or using callable objects: +

+

+     class linear:
+        def __init__(self, a, b):
+            self.a, self.b = a,b
+        def __call__(self, x):
+            return self.a * x + self.b
+
+In both cases: +

+

+     taxes = linear(0.3,2)
+
+gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2. +

+The defaults strategy has the disadvantage that the default arguments +could be accidentally or maliciously overridden. The callable objects +approach has the disadvantage that it is a bit slower and a bit +longer. Note however that a collection of callables can share +their signature via inheritance. EG +

+

+      class exponential(linear):
+         # __init__ inherited
+         def __call__(self, x):
+             return self.a * (x ** self.b)
+
+On comp.lang.python, zenin@bawdycaste.org points out that +an object can encapsulate state for several methods in order +to emulate the "closure" concept from functional programming +languages, for example: +

+

+    class counter:
+        value = 0
+        def set(self, x): self.value = x
+        def up(self): self.value=self.value+1
+        def down(self): self.value=self.value-1
+
+
+    count = counter()
+    inc, dec, reset = count.up, count.down, count.set
+
+Here inc, dec and reset act like "functions which share the +same closure containing the variable count.value" (if you +like that way of thinking). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Sep 25 08:38:35 1998 by +Aaron Watters +

+ +


+

6.28. Why do I get a SyntaxError for a 'continue' inside a 'try'?

+This is an implementation limitation, +caused by the extremely simple-minded +way Python generates bytecode. The try block pushes something on the +"block stack" which the continue would have to pop off again. The +current code generator doesn't have the data structures around so that +'continue' can generate the right code. +

+Note that JPython doesn't have this restriction! +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 22 15:01:07 1998 by +GvR +

+ +


+

6.29. Why can't raw strings (r-strings) end with a backslash?

+More precisely, they can't end with an odd number of backslashes: +the unpaired backslash at the end escapes the closing quote character, +leaving an unterminated string. +

+Raw strings were designed to ease creating input for processors (chiefly +regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose. +

+If you're trying to build Windows pathnames, note that all Windows system calls accept forward slashes too: +

+

+    f = open("/mydir/file.txt") # works fine!
+
+If you're trying to build a pathname for a DOS command, try e.g. one of +

+

+    dir = r"\this\is\my\dos\dir" "\\"
+    dir = r"\this\is\my\dos\dir\ "[:-1]
+    dir = "\\this\\is\\my\\dos\\dir\\"
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jul 13 20:50:20 1998 by +Tim Peters +

+ +


+

6.30. Why can't I use an assignment in an expression?

+Many people used to C or Perl complain that they want to be able to +use e.g. this C idiom: +

+

+    while (line = readline(f)) {
+        ...do something with line...
+    }
+
+where in Python you're forced to write this: +

+

+    while 1:
+        line = f.readline()
+        if not line:
+            break
+        ...do something with line...
+
+This issue comes up in the Python newsgroup with alarming frequency +-- search Deja News for past messages about assignment expression. +The reason for not allowing assignment in Python expressions +is a common, hard-to-find bug in those other languages, +caused by this construct: +

+

+    if (x = 0) {
+        ...error handling...
+    }
+    else {
+        ...code that only works for nonzero x...
+    }
+
+Many alternatives have been proposed. Most are hacks that save some +typing but use arbitrary or cryptic syntax or keywords, +and fail the simple criterion that I use for language change proposals: +it should intuitively suggest the proper meaning to a human reader +who has not yet been introduced with the construct. +

+The earliest time something can be done about this will be with +Python 2.0 -- if it is decided that it is worth fixing. +An interesting phenomenon is that most experienced Python programmers +recognize the "while 1" idiom and don't seem to be missing the +assignment in expression construct much; it's only the newcomers +who express a strong desire to add this to the language. +

+One fairly elegant solution would be to introduce a new operator +for assignment in expressions spelled ":=" -- this avoids the "=" +instead of "==" problem. It would have the same precedence +as comparison operators but the parser would flag combination with +other comparisons (without disambiguating parentheses) as an error. +

+Finally -- there's an alternative way of spelling this that seems +attractive but is generally less robust than the "while 1" solution: +

+

+    line = f.readline()
+    while line:
+        ...do something with line...
+        line = f.readline()
+
+The problem with this is that if you change your mind about exactly +how you get the next line (e.g. you want to change it into +sys.stdin.readline()) you have to remember to change two places +in your program -- the second one hidden at the bottom of the loop. +

+ +Edit this entry / +Log info + +/ Last changed on Tue May 18 00:57:41 1999 by +Andrew Dalke +

+ +


+

6.31. Why doesn't Python have a "with" statement like some other languages?

+Basically, because such a construct would be terribly ambiguous. Thanks to Carlos Ribeiro for the following remarks: +

+Some languages, such as Object Pascal, Delphi, and C++, use static types. So it is possible to know, in an unambiguous way, what member is being assigned in a "with" clause. This is the main point - the compiler always knows the scope of every variable at compile time. +

+Python uses dynamic types. It is impossible to know in advance which +attribute will be referenced at runtime. Member attributes may be added or removed from objects on the fly. This would make it impossible to know, from a simple reading, what attribute is being referenced - a local one, a global one, or a member attribute. +

+For instance, take the following snippet (it is incomplete btw, just to +give you the idea): +

+

+   def with_is_broken(a):
+      with a:
+         print x
+
+The snippet assumes that "a" must have a member attribute called "x". +However, there is nothing in Python that guarantees that. What should +happen if "a" is, let us say, an integer? And if I have a global variable named "x", will it end up being used inside the with block? As you see, the dynamic nature of Python makes such choices much harder. +

+The primary benefit of "with" and similar language features (reduction of code volume) can, however, easily be achieved in Python by assignment. Instead of: +

+

+    function(args).dict[index][index].a = 21
+    function(args).dict[index][index].b = 42
+    function(args).dict[index][index].c = 63
+
+would become: +

+

+    ref = function(args).dict[index][index]
+    ref.a = 21
+    ref.b = 42
+    ref.c = 63
+
+This also has the happy side-effect of increasing execution speed, since name bindings are resolved at run-time in Python, and the second method only needs to perform the resolution once. If the referenced object does not have a, b and c attributes, of course, the end result is still a run-time exception. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jan 11 14:32:58 2002 by +Steve Holden +

+ +


+

6.32. Why are colons required for if/while/def/class?

+The colon is required primarily to enhance readability (one of the +results of the experimental ABC language). Consider this: +

+

+    if a==b
+        print a
+
+versus +

+

+    if a==b:
+        print a
+
+Notice how the second one is slightly easier to read. Notice further how +a colon sets off the example in the second line of this FAQ answer; it's +a standard usage in English. Finally, the colon makes it easier for +editors with syntax highlighting. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 07:22:57 2002 by +Matthias Urlichs +

+ +


+

6.33. Can't we get rid of the Global Interpreter Lock?

+The Global Interpreter Lock (GIL) is often seen as a hindrance to +Python's deployment on high-end multiprocessor server machines, +because a multi-threaded Python program effectively only uses +one CPU, due to the insistence that (almost) all Python code +can only run while the GIL is held. +

+Back in the days of Python 1.5, Greg Stein actually implemented +a comprehensive patch set ("free threading") +that removed the GIL, replacing it with +fine-grained locking. Unfortunately, even on Windows (where locks +are very efficient) this ran ordinary Python code about twice as +slow as the interpreter using the GIL. On Linux the performance +loss was even worse (pthread locks aren't as efficient). +

+Since then, the idea of getting rid of the GIL has occasionally +come up but nobody has found a way to deal with the expected slowdown; +Greg's free threading patch set has not been kept up-to-date for +later Python versions. +

+This doesn't mean that you can't make good use of Python on +multi-CPU machines! You just have to be creative with dividing +the work up between multiple processes rather than multiple +threads. +

+

+It has been suggested that the GIL should be a per-interpreter-state +lock rather than truly global; interpreters then wouldn't be able +to share objects. Unfortunately, this isn't likely to happen either. +

+It would be a tremendous amount of work, because many object +implementations currently have global state. E.g. small ints and +small strings are cached; these caches would have to be moved to the +interpreter state. Other object types have their own free list; these +free lists would have to be moved to the interpreter state. And so +on. +

+And I doubt that it can even be done in finite time, because the same +problem exists for 3rd party extensions. It is likely that 3rd party +extensions are being written at a faster rate than you can convert +them to store all their global state in the interpreter state. +

+And finally, once you have multiple interpreters not sharing any +state, what have you gained over running each interpreter +in a separate process? +

+ +Edit this entry / +Log info + +/ Last changed on Fri Feb 7 16:34:01 2003 by +GvR +

+ +


+

7. Using Python on non-UNIX platforms

+ +
+

7.1. Is there a Mac version of Python?

+Yes, it is maintained by Jack Jansen. See Jack's MacPython Page: +

+

+  http://www.cwi.nl/~jack/macpython.html
+
+

+ +Edit this entry / +Log info + +/ Last changed on Fri May 4 09:33:42 2001 by +GvR +

+ +


+

7.2. Are there DOS and Windows versions of Python?

+Yes. The core windows binaries are available from http://www.python.org/windows/. There is a plethora of Windows extensions available, including a large number of not-always-compatible GUI toolkits. The core binaries include the standard Tkinter GUI extension. +

+Most windows extensions can be found (or referenced) at http://www.python.org/windows/ +

+Windows 3.1/DOS support seems to have dropped off recently. You may need to settle for an old version of Python one these platforms. One such port is WPY +

+WPY: Ports to DOS, Windows 3.1(1), Windows 95, Windows NT and OS/2. +Also contains a GUI package that offers portability between Windows +(not DOS) and Unix, and native look and feel on both. +ftp://ftp.python.org/pub/python/wpy/. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jun 2 20:21:57 1998 by +Mark Hammond +

+ +


+

7.3. Is there an OS/2 version of Python?

+Yes, see http://www.python.org/download/download_os2.html. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 7 11:33:16 1999 by +GvR +

+ +


+

7.4. Is there a VMS version of Python?

+Jean-François Piéronne has ported 2.1.3 to OpenVMS. It can be found at +<http://vmspython.dyndns.org/>. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Sep 19 15:40:38 2002 by +Skip Montanaro +

+ +


+

7.5. What about IBM mainframes, or other non-UNIX platforms?

+I haven't heard about these, except I remember hearing about an +OS/9 port and a port to Vxworks (both operating systems for embedded +systems). If you're interested in any of this, go directly to the +newsgroup and ask there, you may find exactly what you need. For +example, a port to MPE/iX 5.0 on HP3000 computers was just announced, +see http://www.allegro.com/software/. +

+On the IBM mainframe side, for Z/OS there's a port of python 1.4 that goes with their open-unix package, formely OpenEdition MVS, (http://www-1.ibm.com/servers/eserver/zseries/zos/unix/python.html). On a side note, there's also a java vm ported - so, in theory, jython could run too. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Nov 18 03:18:39 2002 by +Bruno Jessen +

+ +


+

7.6. Where are the source or Makefiles for the non-UNIX versions?

+The standard sources can (almost) be used. Additional sources can +be found in the platform-specific subdirectories of the distribution. +

+ +Edit this entry / +Log info +

+ +


+

7.7. What is the status and support for the non-UNIX versions?

+I don't have access to most of these platforms, so in general I am +dependent on material submitted by volunteers. However I strive to +integrate all changes needed to get it to compile on a particular +platform back into the standard sources, so porting of the next +version to the various non-UNIX platforms should be easy. +(Note that Linux is classified as a UNIX platform here. :-) +

+Some specific platforms: +

+Windows: all versions (95, 98, ME, NT, 2000, XP) are supported, +all python.org releases come with a Windows installer. +

+MacOS: Jack Jansen does an admirable job of keeping the Mac version +up to date (both MacOS X and older versions); +see http://www.cwi.nl/~jack/macpython.html +

+For all supported platforms, see http://www.python.org/download/ +(follow the link to "Other platforms" for less common platforms) +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:34:24 2002 by +GvR +

+ +


+

7.8. I have a PC version but it appears to be only a binary. Where's the library?

+If you are running any version of Windows, then you have the wrong distribution. The FAQ lists current Windows versions. Notably, Pythonwin and wpy provide fully functional installations. +

+But if you are sure you have the only distribution with a hope of working on +your system, then... +

+You still need to copy the files from the distribution directory +"python/Lib" to your system. If you don't have the full distribution, +you can get the file lib<version>.tar.gz from most ftp sites carrying +Python; this is a subset of the distribution containing just those +files, e.g. ftp://ftp.python.org/pub/python/src/lib1.4.tar.gz. +

+Once you have installed the library, you need to point sys.path to it. +Assuming the library is in C:\misc\python\lib, the following commands +will point your Python interpreter to it (note the doubled backslashes +-- you can also use single forward slashes instead): +

+

+        >>> import sys
+        >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
+        >>>
+
+For a more permanent effect, set the environment variable PYTHONPATH, +as follows (talking to a DOS prompt): +

+

+        C> SET PYTHONPATH=C:\misc\python\lib
+
+

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 16:28:27 1997 by +Ken Manheimer +

+ +


+

7.9. Where's the documentation for the Mac or PC version?

+The documentation for the Unix version also applies to the Mac and +PC versions. Where applicable, differences are indicated in the text. +

+ +Edit this entry / +Log info +

+ +


+

7.10. How do I create a Python program file on the Mac or PC?

+Use an external editor. On the Mac, BBEdit seems to be a popular +no-frills text editor. I work like this: start the interpreter; edit +a module file using BBedit; import and test it in the interpreter; +edit again in BBedit; then use the built-in function reload() to +re-read the imported module; etc. In the 1.4 distribution +you will find a BBEdit extension that makes life a little easier: +it can tell the interpreter to execute the current window. +See :Mac:Tools:BBPy:README. +

+Regarding the same question for the PC, Kurt Wm. Hemr writes: "While +anyone with a pulse could certainly figure out how to do the same on +MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows. +Not only can you easily resave and "reload()" from Python after making +changes, but since WinNot auto-copies to the clipboard any text you +select, you can simply select the entire procedure (function) which +you changed in WinNot, switch to QWPython, and shift-ins to reenter +the changed program unit." +

+If you're using Windows95 or Windows NT, you should also know about +PythonWin, which provides a GUI framework, with an mouse-driven +editor, an object browser, and a GUI-based debugger. See +

+       http://www.python.org/ftp/python/pythonwin/
+
+for details. +

+ +Edit this entry / +Log info + +/ Last changed on Sun May 25 10:04:25 1997 by +GvR +

+ +


+

7.11. How can I use Tkinter on Windows 95/NT?

+Starting from Python 1.5, it's very easy -- just download and install +Python and Tcl/Tk and you're in business. See +

+

+  http://www.python.org/download/download_windows.html
+
+One warning: don't attempt to use Tkinter from PythonWin +(Mark Hammond's IDE). Use it from the command line interface +(python.exe) or the windowless interpreter (pythonw.exe). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 12 09:32:48 1998 by +GvR +

+ +


+

7.12. cgi.py (or other CGI programming) doesn't work sometimes on NT or win95!

+Be sure you have the latest python.exe, that you are using +python.exe rather than a GUI version of python and that you +have configured the server to execute +

+

+     "...\python.exe -u ..."
+
+for the cgi execution. The -u (unbuffered) option on NT and +win95 prevents the interpreter from altering newlines in the +standard input and output. Without it post/multipart requests +will seem to have the wrong length and binary (eg, GIF) +responses may get garbled (resulting in, eg, a "broken image"). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jul 30 10:48:02 1997 by +aaron watters +

+ +


+

7.13. Why doesn't os.popen() work in PythonWin on NT?

+The reason that os.popen() doesn't work from within PythonWin is due to a bug in Microsoft's C Runtime Library (CRT). The CRT assumes you have a Win32 console attached to the process. +

+You should use the win32pipe module's popen() instead which doesn't depend on having an attached Win32 console. +

+Example: +

+ import win32pipe
+ f = win32pipe.popen('dir /c c:\\')
+ print f.readlines()
+ f.close()
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 31 15:34:09 1997 by +Bill Tutt +

+ +


+

7.14. How do I use different functionality on different platforms with the same program?

+Remember that Python is extremely dynamic and that you +can use this dynamism to configure a program at run-time to +use available functionality on different platforms. For example +you can test the sys.platform and import different modules based +on its value. +

+

+   import sys
+   if sys.platform == "win32":
+      import win32pipe
+      popen = win32pipe.popen
+   else:
+      import os
+      popen = os.popen
+
+(See FAQ 7.13 for an explanation of why you might want to +do something like this.) Also you can try to import a module +and use a fallback if the import fails: +

+

+    try:
+         import really_fast_implementation
+         choice = really_fast_implementation
+    except ImportError:
+         import slower_implementation
+         choice = slower_implementation
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:39:06 1997 by +aaron watters +

+ +


+

7.15. Is there an Amiga version of Python?

+Yes. See the AmigaPython homepage at http://www.bigfoot.com/~irmen/python.html. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 14 06:53:32 1998 by +Irmen de Jong +

+ +


+

7.16. Why doesn't os.popen()/win32pipe.popen() work on Win9x?

+There is a bug in Win9x that prevents os.popen/win32pipe.popen* from working. The good news is there is a way to work around this problem. +The Microsoft Knowledge Base article that you need to lookup is: Q150956. You will find links to the knowledge base at: +http://www.microsoft.com/kb. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 25 10:45:38 1999 by +Bill Tutt +

+ +


+

8. Python on Windows

+ +
+

8.1. Using Python for CGI on Microsoft Windows

+** Setting up the Microsoft IIS Server/Peer Server +

+On the Microsoft IIS +server or on the Win95 MS Personal Web Server +you set up python in the same way that you +would set up any other scripting engine. +

+Run regedt32 and go to: +

+HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\ScriptMap +

+and enter the following line (making any specific changes that your system may need) +

+.py :REG_SZ: c:\<path to python>\python.exe -u %s %s +

+This line will allow you to call your script with a simple reference like: +http://yourserver/scripts/yourscript.py +provided "scripts" is an "executable" directory for your server (which +it usually is by default). +The "-u" flag specifies unbuffered and binary mode for stdin - needed when working with binary data +

+In addition, it is recommended by people who would know that using ".py" may +not be a good idea for the file extensions when used in this context +(you might want to reserve *.py for support modules and use *.cgi or *.cgp +for "main program" scripts). +However, that issue is beyond this Windows FAQ entry. +

+

+** Apache configuration +

+In the Apache configuration file httpd.conf, add the following line at +the end of the file: +

+ScriptInterpreterSource Registry +

+Then, give your Python CGI-scripts the extension .py and put them in the cgi-bin directory. +

+

+** Netscape Servers: +Information on this topic exists at: +http://home.netscape.com/comprod/server_central/support/fasttrack_man/programs.htm#1010870 +

+ +Edit this entry / +Log info + +/ Last changed on Wed Mar 27 12:25:54 2002 by +Gerhard Häring +

+ +


+

8.2. How to check for a keypress without blocking?

+Use the msvcrt module. This is a standard Windows-specific extensions +in Python 1.5 and beyond. It defines a function kbhit() which checks +whether a keyboard hit is present; also getch() which gets one +character without echo. Plus a few other goodies. +

+(Search for "keypress" to find an answer for Unix as well.) +

+ +Edit this entry / +Log info + +/ Last changed on Mon Mar 30 16:21:46 1998 by +GvR +

+ +


+

8.3. $PYTHONPATH

+In MS-DOS derived environments, a unix variable such as $PYTHONPATH is +set as PYTHONPATH, without the dollar sign. PYTHONPATH is useful for +specifying the location of library files. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 11 00:41:26 1998 by +Gvr +

+ +


+

8.4. dedent syntax errors

+The FAQ does not recommend using tabs, and Guido's Python Style Guide recommends 4 spaces for distributed Python code; this is also the Emacs python-mode default; see +

+

+    http://www.python.org/doc/essays/styleguide.html
+
+Under any editor mixing tabs and spaces is a bad idea. MSVC is no different in this respect, and is easily configured to use spaces: Take Tools -> Options -> Tabs, and for file type "Default" set "Tab size" and "Indent size" to 4, and select the "Insert spaces" radio button. +

+If you suspect mixed tabs and spaces are causing problems in leading whitespace, run Python with the -t switch or, run Tools/Scripts/tabnanny.py to check a directory tree in batch mode. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Feb 12 15:04:14 2001 by +Steve Holden +

+ +


+

8.5. How do I emulate os.kill() in Windows?

+Use win32api: +

+

+    def kill(pid):
+        """kill function for Win32"""
+        import win32api
+        handle = win32api.OpenProcess(1, 0, pid)
+        return (0 != win32api.TerminateProcess(handle, 0))
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sat Aug 8 18:55:06 1998 by +Jeff Bauer +

+ +


+

8.6. Why does os.path.isdir() fail on NT shared directories?

+The solution appears to be always append the "\\" on +the end of shared drives. +

+

+  >>> import os
+  >>> os.path.isdir( '\\\\rorschach\\public')
+  0
+  >>> os.path.isdir( '\\\\rorschach\\public\\')
+  1
+
+[Blake Winton responds:] +I've had the same problem doing "Start >> Run" and then a +directory on a shared drive. If I use "\\rorschach\public", +it will fail, but if I use "\\rorschach\public\", it will +work. For that matter, os.stat() does the same thing (well, +it gives an error for "\\\\rorschach\\public", but you get +the idea)... +

+I've got a theory about why this happens, but it's only +a theory. NT knows the difference between shared directories, +and regular directories. "\\rorschach\public" isn't a +directory, it's _really_ an IPC abstraction. This is sort +of lended credence to by the fact that when you're mapping +a network drive, you can't map "\\rorschach\public\utils", +but only "\\rorschach\public". +

+[Clarification by funkster@midwinter.com] +It's not actually a Python +question, as Python is working just fine; it's clearing up something +a bit muddled about Windows networked drives. +

+It helps to think of share points as being like drive letters. +Example: +

+        k: is not a directory
+        k:\ is a directory
+        k:\media is a directory
+        k:\media\ is not a directory
+
+The same rules apply if you substitute "k:" with "\\conky\foo": +
+        \\conky\foo  is not a directory
+        \\conky\foo\ is a directory
+        \\conky\foo\media is a directory
+        \\conky\foo\media\ is not a directory
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sun Jan 31 08:44:48 1999 by +GvR +

+ +


+

8.7. PyRun_SimpleFile() crashes on Windows but not on Unix

+I've seen a number of reports of PyRun_SimpleFile() failing +in a Windows port of an application embedding Python that worked +fine on Unix. PyRun_SimpleString() works fine on both platforms. +

+I think this happens because the application was compiled with a +different set of compiler flags than Python15.DLL. It seems that some +compiler flags affect the standard I/O library in such a way that +using different flags makes calls fail. You need to set it for +the non-debug multi-threaded DLL (/MD on the command line, or can be set via MSVC under Project Settings->C++/Code Generation then the "Use rum-time library" dropdown.) +

+Also note that you can not mix-and-match Debug and Release versions. If you wish to use the Debug Multithreaded DLL, then your module _must_ have an "_d" appended to the base name. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Nov 17 17:37:07 1999 by +Mark Hammond +

+ +


+

8.8. Import of _tkinter fails on Windows 95/98

+Sometimes, the import of _tkinter fails on Windows 95 or 98, +complaining with a message like the following: +

+

+  ImportError: DLL load failed: One of the library files needed
+  to run this application cannot be found.
+
+It could be that you haven't installed Tcl/Tk, but if you did +install Tcl/Tk, and the Wish application works correctly, +the problem may be that its installer didn't +manage to edit the autoexec.bat file correctly. It tries to add a +statement that changes the PATH environment variable to include +the Tcl/Tk 'bin' subdirectory, but sometimes this edit doesn't +quite work. Opening it with notepad usually reveals what the +problem is. +

+(One additional hint, noted by David Szafranski: you can't use +long filenames here; e.g. use C:\PROGRA~1\Tcl\bin instead of +C:\Program Files\Tcl\bin.) +

+ +Edit this entry / +Log info + +/ Last changed on Wed Dec 2 22:32:41 1998 by +GvR +

+ +


+

8.9. Can't extract the downloaded documentation on Windows

+Sometimes, when you download the documentation package to a Windows +machine using a web browser, the file extension of the saved file +ends up being .EXE. This is a mistake; the extension should be .TGZ. +

+Simply rename the downloaded file to have the .TGZ extension, and +WinZip will be able to handle it. (If your copy of WinZip doesn't, +get a newer one from http://www.winzip.com.) +

+ +Edit this entry / +Log info + +/ Last changed on Sat Nov 21 13:41:35 1998 by +GvR +

+ +


+

8.10. Can't get Py_RunSimpleFile() to work.

+This is very sensitive to the compiler vendor, version and (perhaps) +even options. If the FILE* structure in your embedding program isn't +the same as is assumed by the Python interpreter it won't work. +

+The Python 1.5.* DLLs (python15.dll) are all compiled +with MS VC++ 5.0 and with multithreading-DLL options (/MD, I think). +

+If you can't change compilers or flags, try using Py_RunSimpleString(). +A trick to get it to run an arbitrary file is to construct a call to +execfile() with the name of your file as argument. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jan 13 10:58:14 1999 by +GvR +

+ +


+

8.11. Where is Freeze for Windows?

+("Freeze" is a program that allows you to ship a Python program +as a single stand-alone executable file. It is not a compiler, +your programs don't run any faster, but they are more easily +distributable (to platforms with the same OS and CPU). Read the +README file of the freeze program for more disclaimers.) +

+You can use freeze on Windows, but you must download the source +tree (see http://www.python.org/download/download_source.html). +This is recommended for Python 1.5.2 (and betas thereof) only; +older versions don't quite work. +

+You need the Microsoft VC++ 5.0 compiler (maybe it works with +6.0 too). You probably need to build Python -- the project files +are all in the PCbuild directory. +

+The freeze program is in the Tools\freeze subdirectory of the source +tree. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Feb 17 18:47:24 1999 by +GvR +

+ +


+

8.12. Is a *.pyd file the same as a DLL?

+Yes, .pyd files are dll's. But there are a few differences. If you +have a DLL named foo.pyd, then it must have a function initfoo(). You +can then write Python "import foo", and Python will search for foo.pyd +(as well as foo.py, foo.pyc) and if it finds it, will attempt to call +initfoo() to initialize it. You do not link your .exe with foo.lib, +as that would cause Windows to require the DLL to be present. +

+Note that the search path for foo.pyd is PYTHONPATH, not the same as +the path that Windows uses to search for foo.dll. Also, foo.pyd need +not be present to run your program, whereas if you linked your program +with a dll, the dll is required. Of course, foo.pyd is required if +you want to say "import foo". In a dll, linkage is declared in the +source code with __declspec(dllexport). In a .pyd, linkage is defined +in a list of available functions. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Nov 23 02:40:08 1999 by +Jameson Quinn +

+ +


+

8.13. Missing cw3215mt.dll (or missing cw3215.dll)

+Sometimes, when using Tkinter on Windows, you get an error that +cw3215mt.dll or cw3215.dll is missing. +

+Cause: you have an old Tcl/Tk DLL built with cygwin in your path +(probably C:\Windows). You must use the Tcl/Tk DLLs from the +standard Tcl/Tk installation (Python 1.5.2 comes with one). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 11 00:54:13 1999 by +GvR +

+ +


+

8.14. How to make python scripts executable:

+[Blake Coverett] +

+Win2K: +

+The standard installer already associates the .py extension with a file type +(Python.File) and gives that file type an open command that runs the +interpreter (D:\Program Files\Python\python.exe "%1" %*). This is enough to +make scripts executable from the command prompt as 'foo.py'. If you'd +rather be able to execute the script by simple typing 'foo' with no +extension you need to add .py to the PATHEXT environment variable. +

+WinNT: +

+The steps taken by the installed as described above allow you do run a +script with 'foo.py', but a long time bug in the NT command processor +prevents you from redirecting the input or output of any script executed in +this way. This is often important. +

+An appropriate incantation for making a Python script executable under WinNT +is to give the file an extension of .cmd and add the following as the first +line: +

+

+    @setlocal enableextensions & python -x %~f0 %* & goto :EOF
+
+Win9x: +

+[Due to Bruce Eckel] +

+

+  @echo off
+  rem = """
+  rem run python on this bat file. Needs the full path where
+  rem you keep your python files. The -x causes python to skip
+  rem the first line of the file:
+  python -x c:\aaa\Python\\"%0".bat %1 %2 %3 %4 %5 %6 %7 %8 %9
+  goto endofpython
+  rem """
+
+
+  # The python program goes here:
+
+
+  print "hello, Python"
+
+
+  # For the end of the batch file:
+  rem = """
+  :endofpython
+  rem """
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Nov 30 10:25:17 1999 by +GvR +

+ +


+

8.15. Warning about CTL3D32 version from installer

+The Python installer issues a warning like this: +

+

+  This version uses CTL3D32.DLL whitch is not the correct version.
+  This version is used for windows NT applications only.
+
+[Tim Peters] +This is a Microsoft DLL, and a notorious +source of problems. The msg means what it says: you have the wrong version +of this DLL for your operating system. The Python installation did not +cause this -- something else you installed previous to this overwrote the +DLL that came with your OS (probably older shareware of some sort, but +there's no way to tell now). If you search for "CTL3D32" using any search +engine (AltaVista, for example), you'll find hundreds and hundreds of web +pages complaining about the same problem with all sorts of installation +programs. They'll point you to ways to get the correct version reinstalled +on your system (since Python doesn't cause this, we can't fix it). +

+David A Burton has written a little program to fix this. Go to +http://www.burtonsys.com/download.html and click on "ctl3dfix.zip" +

+ +Edit this entry / +Log info + +/ Last changed on Thu Oct 26 15:42:00 2000 by +GvR +

+ +


+

8.16. How can I embed Python into a Windows application?

+Edward K. Ream <edream@tds.net> writes +

+When '##' appears in a file name below, it is an abbreviated version number. For example, for Python 2.1.1, ## will be replaced by 21. +

+Embedding the Python interpreter in a Windows app can be summarized as +follows: +

+1. Do _not_ build Python into your .exe file directly. On Windows, +Python must be a DLL to handle importing modules that are themselves +DLL's. (This is the first key undocumented fact.) Instead, link to +python##.dll; it is typically installed in c:\Windows\System. +

+You can link to Python statically or dynamically. Linking statically +means linking against python##.lib The drawback is that your app won't +run if python##.dll does not exist on your system. +

+General note: python##.lib is the so-called "import lib" corresponding +to python.dll. It merely defines symbols for the linker. +

+Borland note: convert python##.lib to OMF format using Coff2Omf.exe +first. +

+Linking dynamically greatly simplifies link options; everything happens +at run time. Your code must load python##.dll using the Windows +LoadLibraryEx() routine. The code must also use access routines and +data in python##.dll (that is, Python's C API's) using pointers +obtained by the Windows GetProcAddress() routine. Macros can make +using these pointers transparent to any C code that calls routines in +Python's C API. +

+2. If you use SWIG, it is easy to create a Python "extension module" +that will make the app's data and methods available to Python. SWIG +will handle just about all the grungy details for you. The result is C +code that you link _into your .exe file_ (!) You do _not_ have to +create a DLL file, and this also simplifies linking. +

+3. SWIG will create an init function (a C function) whose name depends +on the name of the extension module. For example, if the name of the +module is leo, the init function will be called initleo(). If you use +SWIG shadow classes, as you should, the init function will be called +initleoc(). This initializes a mostly hidden helper class used by the +shadow class. +

+The reason you can link the C code in step 2 into your .exe file is that +calling the initialization function is equivalent to importing the +module into Python! (This is the second key undocumented fact.) +

+4. In short, you can use the following code to initialize the Python +interpreter with your extension module. +

+

+    #include "python.h"
+    ...
+    Py_Initialize();  // Initialize Python.
+    initmyAppc();  // Initialize (import) the helper class. 
+    PyRun_SimpleString("import myApp") ;  // Import the shadow class.
+
+5. There are two problems with Python's C API which will become apparent +if you use a compiler other than MSVC, the compiler used to build +python##.dll. +

+Problem 1: The so-called "Very High Level" functions that take FILE * +arguments will not work in a multi-compiler environment; each compiler's +notion of a struct FILE will be different. From an implementation +standpoint these are very _low_ level functions. +

+Problem 2: SWIG generates the following code when generating wrappers to +void functions: +

+

+    Py_INCREF(Py_None);
+    _resultobj = Py_None;
+    return _resultobj;
+
+Alas, Py_None is a macro that expands to a reference to a complex data +structure called _Py_NoneStruct inside python##.dll. Again, this code +will fail in a mult-compiler environment. Replace such code by: +

+

+    return Py_BuildValue("");
+
+It may be possible to use SWIG's %typemap command to make the change +automatically, though I have not been able to get this to work (I'm a +complete SWIG newbie). +

+6. Using a Python shell script to put up a Python interpreter window +from inside your Windows app is not a good idea; the resulting window +will be independent of your app's windowing system. Rather, you (or the +wxPythonWindow class) should create a "native" interpreter window. It +is easy to connect that window to the Python interpreter. You can +redirect Python's i/o to _any_ object that supports read and write, so +all you need is a Python object (defined in your extension module) that +contains read() and write() methods. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jan 31 16:29:34 2002 by +Victor Kryukov +

+ +


+

8.17. Setting up IIS 5 to use Python for CGI

+In order to set up Internet Information Services 5 to use Python for CGI processing, please see the following links: +

+http://www.e-coli.net/pyiis_server.html (for Win2k Server) +http://www.e-coli.net/pyiis.html (for Win2k pro) +

+ +Edit this entry / +Log info + +/ Last changed on Fri Mar 22 22:05:51 2002 by +douglas savitsky +

+ +


+

8.18. How do I run a Python program under Windows?

+This is not necessarily quite the straightforward question it appears +to be. If you are already familiar with running programs from the +Windows command line then everything will seem really easy and +obvious. If your computer experience is limited then you might need a +little more guidance. Also there are differences between Windows 95, +98, NT, ME, 2000 and XP which can add to the confusion. You might +think of this as "why I pay software support charges" if you have a +helpful and friendly administrator to help you set things up without +having to understand all this yourself. If so, then great! Show them +this page and it should be a done deal. +

+Unless you use some sort of integrated development environment (such +as PythonWin or IDLE, to name only two in a growing family) then you +will end up typing Windows commands into what is variously referred +to as a "DOS window" or "Command prompt window". Usually you can +create such a window from your Start menu (under Windows 2000 I use +"Start | Programs | Accessories | Command Prompt"). You should be +able to recognize when you have started such a window because you will +see a Windows "command prompt", which usually looks like this: +

+

+    C:\>
+
+The letter may be different, and there might be other things after it, +so you might just as easily see something like: +

+

+    D:\Steve\Projects\Python>
+
+depending on how your computer has been set up and what else you have +recently done with it. Once you have started such a window, you are +well on the way to running Python programs. +

+You need to realize that your Python scripts have to be processed by +another program, usually called the "Python interpreter". The +interpreter reads your script, "compiles" it into "Python bytecodes" +(which are instructions for an imaginary computer known as the "Python +Virtual Machine") and then executes the bytecodes to run your +program. So, how do you arrange for the interpreter to handle your +Python? +

+First, you need to make sure that your command window recognises the +word "python" as an instruction to start the interpreter. If you have +opened a command window, you should try entering the command: +

+

+    python
+
+and hitting return. If you then see something like: +

+

+    Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
+    Type "help", "copyright", "credits" or "license" for more information.
+    >>>
+
+then this part of the job has been correctly managed during Python's +installation process, and you have started the interpreter in +"interactive mode". That means you can enter Python statements or +expressions interactively and have them executed or evaluated while +you wait. This is one of Python's strongest features, but it takes a +little getting used to. Check it by entering a few expressions of your +choice and seeing the results... +

+

+    >>> print "Hello"
+    Hello
+    >>> "Hello" * 3
+    HelloHelloHello
+
+When you want to end your interactive Python session, enter a +terminator (hold the Ctrl key down while you enter a Z, then hit the +"Enter" key) to get back to your Windows command prompt. You may also +find that you have a Start-menu entry such as "Start | Programs | +Python 2.2 | Python (command line)" that results in you seeing the +">>>" prompt in a new window. If so, the window will disappear after +you enter the terminator -- Windows runs a single "python" command in +the window, which terminates when you terminate the interpreter. +

+If the "python" command, instead of displaying the interpreter prompt ">>>", gives you a message like +

+

+    'python' is not recognized as an internal or external command,
+    operable program or batch file.
+
+or +

+

+    Bad command or filename
+
+then you need to make sure that your computer knows where to find the +Python interpreter. To do this you will have to modify a setting +called the PATH, which is a just list of directories where Windows +will look for programs. Rather than just enter the right command every +time you create a command window, you should arrange for Python's +installation directory to be added to the PATH of every command window +as it starts. If you installed Python fairly recently then the command +

+

+    dir C:\py*
+
+will probably tell you where it is installed. Alternatively, perhaps +you made a note. Otherwise you will be reduced to a search of your +whole disk ... break out the Windows explorer and use "Tools | Find" +or hit the "Search" button and look for "python.exe". Suppose you +discover that Python is installed in the C:\Python22 directory (the +default at the time of writing) then you should make sure that +entering the command +

+

+    c:\Python22\python
+
+starts up the interpreter as above (and don't forget you'll need a +"CTRL-Z" and an "Enter" to get out of it). Once you have verified the +directory, you need to add it to the start-up routines your computer +goes through. For older versions of Windows the easiest way to do +this is to edit the C:\AUTOEXEC.BAT file. You would want to add a line +like the following to AUTOEXEC.BAT: +

+

+    PATH C:\Python22;%PATH%
+
+For Windows NT, 2000 and (I assume) XP, you will need to add a string +such as +

+

+    ;C:\Python22
+
+to the current setting for the PATH environment variable, which you +will find in the properties window of "My Computer" under the +"Advanced" tab. Note that if you have sufficient privilege you might +get a choice of installing the settings either for the Current User or +for System. The latter is preferred if you want everybody to be able +to run Python on the machine. +

+If you aren't confident doing any of these manipulations yourself, ask +for help! At this stage you may or may not want to reboot your system +to make absolutely sure the new setting has "taken" (don't you love +the way Windows gives you these freqeuent coffee breaks). You probably +won't need to for Windows NT, XP or 2000. You can also avoid it in +earlier versions by editing the file C:\WINDOWS\COMMAND\CMDINIT.BAT +instead of AUTOEXEC.BAT. +

+You should now be able to start a new command window, enter +

+

+    python
+
+at the "C:>" (or whatever) prompt, and see the ">>>" prompt that +indicates the Python interpreter is reading interactive commands. +

+Let's suppose you have a program called "pytest.py" in directory +"C:\Steve\Projects\Python". A session to run that program might look +like this: +

+

+    C:\> cd \Steve\Projects\Python
+    C:\Steve\Projects\Python> python pytest.py
+
+Because you added a file name to the command to start the interpreter, +when it starts up it reads the Python script in the named file, +compiles it, executes it, and terminates (so you see another "C:\>" +prompt). You might also have entered +

+

+    C:\> python \Steve\Projects\Python\pytest.py
+
+if you hadn't wanted to change your current directory. +

+Under NT, 2000 and XP you may well find that the installation process +has also arranged that the command +

+

+    pytest.py
+
+(or, if the file isn't in the current directory) +

+

+    C:\Steve\Projects\Python\pytest.py
+
+will automatically recognize the ".py" extension and run the Python +interpreter on the named file. Using this feature is fine, but some +versions of Windows have bugs which mean that this form isn't exactly +equivalent to using the interpreter explicitly, so be careful. Easier +to remember, for now, that +

+

+    python C:\Steve\Projects\Python\pytest.py
+
+works pretty close to the same, and redirection will work (more) +reliably. +

+The important things to remember are: +

+1. Start Python from the Start Menu, or make sure the PATH is set +correctly so Windows can find the Python interpreter. +

+

+    python
+
+should give you a '>>>" prompt from the Python interpreter. Don't +forget the CTRL-Z and ENTER to terminate the interpreter (and, if you +started the window from the Start Menu, make the window disappear). +

+2. Once this works, you run programs with commands: +

+

+    python {program-file}
+
+3. When you know the commands to use you can build Windows shortcuts +to run the Python interpreter on any of your scripts, naming +particular working directories, and adding them to your menus, but +that's another lessFAQ. Take a look at +

+

+    python --help
+
+if your needs are complex. +

+4. Interactive mode (where you see the ">>>" prompt) is best used +not for running programs, which are better executed as in steps 2 +and 3, but for checking that individual statements and expressions do +what you think they will, and for developing code by experiment. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Aug 20 16:19:53 2002 by +GvR +

+ +


+Python home / +Python FAQ Wizard 1.0.3 / +Feedback to GvR +

Python Powered
+ + --- python2.7-2.7.15.orig/debian/PVER-dbg.README.Debian.in +++ python2.7-2.7.15/debian/PVER-dbg.README.Debian.in @@ -0,0 +1,58 @@ +Contents of the @PVER@-dbg package +------------------------------------- + +For debugging python and extension modules, you may want to add the contents +of /usr/share/doc/@PVER@/gdbinit (found in the @PVER@-dev package) to your +~/.gdbinit file. + +@PVER@-dbg contains two sets of packages: + + - debugging symbols for the standard @PVER@ build. When this package + is installed, gdb will automatically load up the debugging symbols + from it when debugging @PVER@ or one of the included extension + modules. + + - a separate @PVER@-dbg binary, configured --with-pydebug, enabling the + additional debugging code to help debug memory management problems. + +For the latter, all extension modules have to be recompiled to +correctly load with an pydebug enabled build. + + +Debian and Ubuntu specific changes to the debug interpreter +----------------------------------------------------------- +The python2.4 and python2.5 packages in Ubuntu feisty are modified to +first look for extension modules under a different name. + + normal build: foo.so + debug build: foo_d.so foo.so + +This naming schema allows installation of the extension modules into +the same path (The naming is directly taken from the Windows builds +which already uses this naming scheme). + +See https://wiki.ubuntu.com/PyDbgBuilds for more information. + + +Using the python-dbg builds +--------------------------- + + * Call the python-dbg or the pythonX.Y-dbg binaries instead of the + python or pythonX.Y binaries. + + * Debugging a third party extension requires the availabilty of the + extension built for the debug interpreter. For an extension `foo' + make sure that the `python-foo-dbg' package is installed, or else + the interpreter falls back to the extension for the normal build. + The error on fallback is expected. + + * Properties of the debug build are described in + /usr/share/doc/@PVER@/SpecialBuilds.txt.gz. + The debug interpreter is built with Py_DEBUG defined. + + * From SpecialBuilds.txt: This is what is generally meant by "a debug + build" of Python. Py_DEBUG implies LLTRACE, Py_REF_DEBUG, + Py_TRACE_REFS, and PYMALLOC_DEBUG (if WITH_PYMALLOC is enabled). + In addition, C assert()s are enabled (via the C way: by not defining + NDEBUG), and some routines do additional sanity checks inside + "#ifdef Py_DEBUG" blocks. --- python2.7-2.7.15.orig/debian/PVER-dbg.overrides.in +++ python2.7-2.7.15/debian/PVER-dbg.overrides.in @@ -0,0 +1,13 @@ +@PVER@-dbg binary: package-name-doesnt-match-sonames +@PVER@-dbg binary: non-dev-pkg-with-shlib-symlink + +# no, it's not unusual +@PVER@-dbg binary: unusual-interpreter + +# just the gdb debug file +@PVER@-dbg binary: python-script-but-no-python-dep + +# pointless lintian ... +@PVER@-dbg binary: hardening-no-fortify-functions + +@PVER@-dbg binary: command-with-path-in-maintainer-script --- python2.7-2.7.15.orig/debian/PVER-dbg.postinst.in +++ python2.7-2.7.15/debian/PVER-dbg.postinst.in @@ -0,0 +1,19 @@ +#! /bin/sh + +set -e + +if [ "$1" = configure ]; then + files=$(dpkg -L lib@PVER@-dbg@HOST_QUAL@ | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p') + if [ -n "$files" ]; then + /usr/bin/@PVER@ -E -S /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + /usr/bin/@PVER@ -E -S -O /usr/lib/@PVER@/py_compile.py $files + fi + else + echo >&2 "@PVER@-dbg: can't get files for byte-compilation" + fi +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/PVER-dbg.prerm.in +++ python2.7-2.7.15/debian/PVER-dbg.prerm.in @@ -0,0 +1,28 @@ +#! /bin/sh + +set -e + +case "$1" in + remove) + rm -f /usr/lib/debug/usr/bin/@PVER@-gdb.py[co] + rm -f /usr/lib/debug/usr/lib/lib@PVER@.so.1.0-gdb.py[co] + dpkg -L lib@PVER@-dbg@HOST_QUAL@ \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 + ;; + upgrade) + dpkg -L lib@PVER@-dbg@HOST_QUAL@ \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.15.orig/debian/PVER-doc.doc-base.PVER-api.in +++ python2.7-2.7.15/debian/PVER-doc.doc-base.PVER-api.in @@ -0,0 +1,13 @@ +Document: @PVER@-api +Title: Python/C API Reference Manual (v@VER@) +Author: Guido van Rossum +Abstract: This manual documents the API used by C (or C++) programmers who + want to write extension modules or embed Python. It is a + companion to *Extending and Embedding the Python Interpreter*, + which describes the general principles of extension writing but + does not document the API functions in detail. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/c-api/index.html +Files: /usr/share/doc/@PVER@/html/c-api/*.html --- python2.7-2.7.15.orig/debian/PVER-doc.doc-base.PVER-dist.in +++ python2.7-2.7.15/debian/PVER-doc.doc-base.PVER-dist.in @@ -0,0 +1,13 @@ +Document: @PVER@-dist +Title: Distributing Python Modules (v@VER@) +Author: Greg Ward +Abstract: This document describes the Python Distribution Utilities + (``Distutils'') from the module developer's point-of-view, describing + how to use the Distutils to make Python modules and extensions easily + available to a wider audience with very little overhead for + build/release/install mechanics. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/distutils/index.html +Files: /usr/share/doc/@PVER@/html/distutils/*.html --- python2.7-2.7.15.orig/debian/PVER-doc.doc-base.PVER-ext.in +++ python2.7-2.7.15/debian/PVER-doc.doc-base.PVER-ext.in @@ -0,0 +1,16 @@ +Document: @PVER@-ext +Title: Extending and Embedding the Python Interpreter (v@VER@) +Author: Guido van Rossum +Abstract: This document describes how to write modules in C or C++ to extend + the Python interpreter with new modules. Those modules can define + new functions but also new object types and their methods. The + document also describes how to embed the Python interpreter in + another application, for use as an extension language. Finally, + it shows how to compile and link extension modules so that they + can be loaded dynamically (at run time) into the interpreter, if + the underlying operating system supports this feature. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/extending/index.html +Files: /usr/share/doc/@PVER@/html/extending/*.html --- python2.7-2.7.15.orig/debian/PVER-doc.doc-base.PVER-inst.in +++ python2.7-2.7.15/debian/PVER-doc.doc-base.PVER-inst.in @@ -0,0 +1,12 @@ +Document: @PVER@-inst +Title: Installing Python Modules (v@VER@) +Author: Greg Ward +Abstract: This document describes the Python Distribution Utilities + (``Distutils'') from the end-user's point-of-view, describing how to + extend the capabilities of a standard Python installation by building + and installing third-party Python modules and extensions. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/install/index.html +Files: /usr/share/doc/@PVER@/html/install/*.html --- python2.7-2.7.15.orig/debian/PVER-doc.doc-base.PVER-lib.in +++ python2.7-2.7.15/debian/PVER-doc.doc-base.PVER-lib.in @@ -0,0 +1,15 @@ +Document: @PVER@-lib +Title: Python Library Reference (v@VER@) +Author: Guido van Rossum +Abstract: This library reference manual documents Python's standard library, + as well as many optional library modules (which may or may not be + available, depending on whether the underlying platform supports + them and on the configuration choices made at compile time). It + also documents the standard types of the language and its built-in + functions and exceptions, many of which are not or incompletely + documented in the Reference Manual. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/library/index.html +Files: /usr/share/doc/@PVER@/html/library/*.html --- python2.7-2.7.15.orig/debian/PVER-doc.doc-base.PVER-new.in +++ python2.7-2.7.15/debian/PVER-doc.doc-base.PVER-new.in @@ -0,0 +1,10 @@ +Document: @PVER@-new +Title: What's new in Python @VER@ +Author: A.M. Kuchling +Abstract: This documents lists new features and changes worth mentioning + in Python @VER@. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/whatsnew/@VER@.html +Files: /usr/share/doc/@PVER@/html/whatsnew/@VER@.html --- python2.7-2.7.15.orig/debian/PVER-doc.doc-base.PVER-ref.in +++ python2.7-2.7.15/debian/PVER-doc.doc-base.PVER-ref.in @@ -0,0 +1,18 @@ +Document: @PVER@-ref +Title: Python Reference Manual (v@VER@) +Author: Guido van Rossum +Abstract: This reference manual describes the syntax and "core semantics" of + the language. It is terse, but attempts to be exact and complete. + The semantics of non-essential built-in object types and of the + built-in functions and modules are described in the *Python + Library Reference*. For an informal introduction to the language, + see the *Python Tutorial*. For C or C++ programmers, two + additional manuals exist: *Extending and Embedding the Python + Interpreter* describes the high-level picture of how to write a + Python extension module, and the *Python/C API Reference Manual* + describes the interfaces available to C/C++ programmers in detail. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/reference/index.html +Files: /usr/share/doc/@PVER@/html/reference/*.html --- python2.7-2.7.15.orig/debian/PVER-doc.doc-base.PVER-tut.in +++ python2.7-2.7.15/debian/PVER-doc.doc-base.PVER-tut.in @@ -0,0 +1,13 @@ +Document: @PVER@-tut +Title: Python Tutorial (v@VER@) +Author: Guido van Rossum, Fred L. Drake, Jr., editor +Abstract: This tutorial introduces the reader informally to the basic + concepts and features of the Python language and system. It helps + to have a Python interpreter handy for hands-on experience, but + all examples are self-contained, so the tutorial can be read + off-line as well. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/tutorial/index.html +Files: /usr/share/doc/@PVER@/html/tutorial/*.html --- python2.7-2.7.15.orig/debian/PVER-doc.overrides.in +++ python2.7-2.7.15/debian/PVER-doc.overrides.in @@ -0,0 +1,2 @@ +# this is referenced by the html docs +@PVER@-doc binary: extra-license-file --- python2.7-2.7.15.orig/debian/PVER-examples.overrides.in +++ python2.7-2.7.15/debian/PVER-examples.overrides.in @@ -0,0 +1,2 @@ +# don't care about permissions of the example files +@PVER@-examples binary: executable-not-elf-or-script --- python2.7-2.7.15.orig/debian/PVER-minimal.README.Debian.in +++ python2.7-2.7.15/debian/PVER-minimal.README.Debian.in @@ -0,0 +1,157 @@ +Contents of the @PVER@-minimal package +----------------------------------------- + +@PVER@-minimal consists of a minimum set of modules which may be needed +for python scripts used during the boot process. If other packages +are needed in these scripts, don't work around the missing module, but +file a bug report against this package. The modules in this package +are: + + __builtin__ builtin + __future__ module + _abcoll module + _bisect extension + _bytesio extension + _codecs builtin + _collections extension + _fileio extension + _functools extension + _hashlib extensionx + _heapq extension + _io extension + _locale extension + _md5 extension + _random extension + _sha extension + _sha256 extension + _sha512 extension + _socket extension + _sre builtin + _ssl extensionx + _struct extension + _symtable builtin + _sysconfigdata module + _types builtin + _warnings builtin + _weakref extension + _weakrefset module + abc module + atexit module + ConfigParser module + StringIO module + UserDict module + cPickle extension + cStringIO extension + array extension + base64 module + binascii extension + bisect module + cmath extension + calendar module + codecs module + collections module + compileall module + contextlib module + copy module + copy_reg module + datetime extension + dis module + encodings package + errno builtin + exceptions builtin + fcntl extension + fnmatch module + functools module + gc builtin + genericpath module + getopt module + glob module + grp extension + hashlib module + heapq module + imp builtin + inspect module + io module + itertools extension + keyword module + linecache module + locale module + logging package + marshal builtin + math extension + md5 module + opcode module + operator extension + optparse module + os module + pickle module + platform module + popen2 module + posix builtin + posixpath module + pkgutil module + pwd builtin + py_compile module + random module + re module + repr module + runpy module + select extension + sha module + shutil module + signal builtin + socket module + spwd extension + sre module + sre_compile module + sre_constants module + sre_parse module + ssl module + stat module + string module + strop extension + struct module + subprocess module + sys builtin + syslog extension + sysconfig module + tempfile module + textwrap module + time extension + token module + thread builtin + token module + tokenize module + traceback module + types module + unicodedata extension + weakref module + warnings module + zipimport extension + zlib extension + +Included are as well the codecs and stringprep modules, and the encodings +modules for all encodings except the multibyte encodings and the bz2 codec. + +The following modules are excluded, their import is guarded from the +importing module: + + Used in Excluded + ------------ ------------------------------------ + os nt ntpath os2 os2emxpath mac macpath + riscos riscospath riscosenviron + optparse gettext + pickle doctest + subprocess threading + +This list was derived by looking at the modules in the perl-base package, +then adding python specific "core modules". + +TODO's +------ + +- time.strptime cannot be used. The required _strptime module is not + included in the -minimal package yet. _strptime, locale, _locale and + calendar have to be added. + +- modules used very often in the testsuite: copy, cPickle, operator. --- python2.7-2.7.15.orig/debian/PVER-minimal.overrides.in +++ python2.7-2.7.15/debian/PVER-minimal.overrides.in @@ -0,0 +1 @@ +@PVER@-minimal binary: command-with-path-in-maintainer-script --- python2.7-2.7.15.orig/debian/PVER-minimal.postinst.in +++ python2.7-2.7.15/debian/PVER-minimal.postinst.in @@ -0,0 +1,78 @@ +#! /bin/sh + +set -e + +if [ ! -f /etc/@PVER@/sitecustomize.py ]; then + cat <<-EOF + # Empty sitecustomize.py to avoid a dangling symlink +EOF +fi + +case "$1" in + configure) + # Create empty directories in /usr/local + if [ ! -e /usr/local/lib/@PVER@ ]; then + mkdir -p /usr/local/lib/@PVER@ 2> /dev/null || true + chmod 2775 /usr/local/lib/@PVER@ 2> /dev/null || true + chown root:staff /usr/local/lib/@PVER@ 2> /dev/null || true + fi + localsite=/usr/local/lib/@PVER@/dist-packages + if [ ! -e $localsite ]; then + mkdir -p $localsite 2> /dev/null || true + chmod 2775 $localsite 2> /dev/null || true + chown root:staff $localsite 2> /dev/null || true + fi + + if which update-binfmts >/dev/null; then + update-binfmts --import @PVER@ + fi + + ;; +esac + +if [ "$1" = configure ]; then + if ls -L /usr/lib/@PVER@/sitecustomize.py >/dev/null 2>&1; then + filt='cat' + else + filt='fgrep -v sitecustomize.py' + fi + files=$(dpkg -L lib@PVER@-minimal@HOST_QUAL@ \ + | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p' | $filt) + if [ -n "$files" ]; then + /usr/bin/@PVER@ -E -S /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + /usr/bin/@PVER@ -E -S -O /usr/lib/@PVER@/py_compile.py $files + fi + else + echo >&2 "@PVER@-minimal: can't get files for byte-compilation" + fi + bc=no + if [ -z "$2" ] || dpkg --compare-versions "$2" lt 2.7-9 \ + || [ -f /var/lib/python/@PVER@_installed ]; then + bc=yes + fi + if grep -sq '^unsupported-versions[^#]*@PVER@' /usr/share/python/debian_defaults + then + # FIXME: byte compile anyway? + bc=no + fi + if [ "$bc" = yes ]; then + # new installation or installation of first version with hook support + if [ "$DEBIAN_FRONTEND" != noninteractive ]; then + echo "Linking and byte-compiling packages for runtime @PVER@..." + fi + version=$(dpkg -s @PVER@-minimal | awk '/^Version:/ {print $2}') + for hook in /usr/share/python/runtime.d/*.rtinstall; do + [ -x $hook ] || continue + $hook rtinstall @PVER@ "$2" "$version" + done + if [ -f /var/lib/python/@PVER@_installed ]; then + rm -f /var/lib/python/@PVER@_installed + rmdir --ignore-fail-on-non-empty /var/lib/python 2>/dev/null + fi + fi +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/PVER-minimal.postrm.in +++ python2.7-2.7.15/debian/PVER-minimal.postrm.in @@ -0,0 +1,21 @@ +#! /bin/sh + +set -e + +if [ "$1" = "remove" ]; then + + if [ -f /var/lib/python/@PVER@_installed ]; then + rm -f /var/lib/python/@PVER@_installed + rmdir --ignore-fail-on-non-empty /var/lib/python 2>/dev/null + fi +fi + +if [ "$1" = "purge" ]; then + for d in `find /usr/lib/@PVER@ -depth -type d -empty 2> /dev/null`; do \ + while rmdir $d 2> /dev/null; do d=`dirname $d`; done; \ + done +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/PVER-minimal.preinst.in +++ python2.7-2.7.15/debian/PVER-minimal.preinst.in @@ -0,0 +1,39 @@ +#!/bin/sh + +set -e + +syssite=/usr/lib/@PVER@/site-packages +oldsite=/usr/lib/@PVER@/old-site-packages +localsite=/usr/local/lib/@PVER@/dist-packages +syslink=../../${localsite#/usr/*} + +case "$1" in + install) + if [ -z "$2" ] && [ -d $syssite ] && [ ! -h $syssite ]; then + echo "new installation of @PVER@-minimal; $syssite is a directory" + echo "which is expected a symlink to $localsite." + echo "please find the package shipping files in $syssite and" + echo "file a bug report to ship these in /usr/lib/@PVER@/dist-packages instead" + echo "aborting installation of @PVER@-minimal" + exit 1 + fi + + # remember newly installed runtime + mkdir -p /var/lib/python + touch /var/lib/python/@PVER@_installed + ;; + upgrade) + ;; + + abort-upgrade) + ;; + + *) + echo "preinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/PVER-minimal.prerm.in +++ python2.7-2.7.15/debian/PVER-minimal.prerm.in @@ -0,0 +1,36 @@ +#! /bin/sh + +set -e + +case "$1" in + remove) + if [ "$DEBIAN_FRONTEND" != noninteractive ]; then + echo "Unlinking and removing bytecode for runtime @PVER@" + fi + for hook in /usr/share/python/runtime.d/*.rtremove; do + [ -x $hook ] || continue + $hook rtremove @PVER@ || continue + done + + if which update-binfmts >/dev/null; then + update-binfmts --package @PVER@ --remove @PVER@ /usr/bin/@PVER@ + fi + + localsite=/usr/local/lib/@PVER@/dist-packages + [ -d $localsite ] && rmdir $localsite 2>/dev/null || true + [ -d $(dirname $localsite) ] \ + && rmdir $(dirname $localsite) 2>/dev/null || true + ;; + upgrade) + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.15.orig/debian/PVER.desktop.in +++ python2.7-2.7.15/debian/PVER.desktop.in @@ -0,0 +1,10 @@ +[Desktop Entry] +Name=Python (v@VER@) +Comment=Python Interpreter (v@VER@) +Exec=/usr/bin/@PVER@ +Icon=/usr/share/pixmaps/@PVER@.xpm +Terminal=true +Type=Application +Categories=Development; +StartupNotify=true +NoDisplay=true --- python2.7-2.7.15.orig/debian/PVER.overrides.in +++ python2.7-2.7.15/debian/PVER.overrides.in @@ -0,0 +1,16 @@ +# idlelib images +@PVER@ binary: image-file-in-usr-lib + +# yes, we have to +@PVER@ binary: depends-on-python-minimal + +@PVER@ binary: desktop-command-not-in-package +@PVER@ binary: menu-command-not-in-package + +# license file referred by the standard library +@PVER@ binary: extra-license-file + +# no, not useless +@PVER@ binary: manpage-has-useless-whatis-entry + +@PVER@ binary: command-with-path-in-maintainer-script --- python2.7-2.7.15.orig/debian/PVER.postinst.in +++ python2.7-2.7.15/debian/PVER.postinst.in @@ -0,0 +1,41 @@ +#! /bin/sh + +set -e + +case "$1" in + configure) + files=$(dpkg -L lib@PVER@-stdlib@HOST_QUAL@ | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p') + if [ -n "$files" ]; then + /usr/bin/@PVER@ -E -S /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + /usr/bin/@PVER@ -E -S -O /usr/lib/@PVER@/py_compile.py $files + fi + else + echo >&2 "@PVER@: can't get files for byte-compilation" + fi + + # Create empty directories in /usr/local + if [ ! -e /usr/local/lib/python@VER@ ]; then + mkdir -p /usr/local/lib/python@VER@ 2> /dev/null || true + chmod 2775 /usr/local/lib/python@VER@ 2> /dev/null || true + chown root:staff /usr/local/lib/python@VER@ 2> /dev/null || true + fi + if [ ! -e /usr/local/lib/python@VER@/site-packages ]; then + mkdir -p /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + chmod 2775 /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + chown root:staff /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + fi + ;; + + abort-upgrade|abort-remove|abort-deconfigure) + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/PVER.prerm.in +++ python2.7-2.7.15/debian/PVER.prerm.in @@ -0,0 +1,22 @@ +#! /bin/sh + +set -e + +case "$1" in + remove|upgrade) + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +rmdir /usr/local/lib/python@VER@/site-packages 2>/dev/null && \ + rmdir /usr/local/lib/python@VER@ 2>/dev/null || \ + true + +#DEBHELPER# --- python2.7-2.7.15.orig/debian/README.Debian.in +++ python2.7-2.7.15/debian/README.Debian.in @@ -0,0 +1,8 @@ +The documentation for this package is in /usr/share/doc/@PVER@/. + +A draft of the "Debian Python Policy" can be found in + + /usr/share/doc/python + +Sometime it will be moved to /usr/share/doc/debian-policy in the +debian-policy package. --- python2.7-2.7.15.orig/debian/README.PVER.in +++ python2.7-2.7.15/debian/README.PVER.in @@ -0,0 +1,95 @@ + + Python @VER@ for Debian + --------------------- + +This is Python @VER@ packaged for Debian. + +This document contains information specific to the Debian packages of +Python @VER@. + + + + [TODO: This document is not yet up-to-date with the packages.] + +Currently, it features those two main topics: + + 1. Release notes for the Debian packages: + 2. Notes for developers using the Debian Python packages: + +Release notes and documentation from the upstream package are installed +in /usr/share/doc/@PVER@/. + +There's a mailing list for discussion of issues related to Python on Debian +systems: debian-python@lists.debian.org. The list is not intended for +general Python problems, but as a forum for maintainers of Python-related +packages and interested third parties. + + + +1. Release notes for the Debian packages: + + +Results of the regression test: +------------------------------ + +The package does successfully run the regression tests for all included +modules. Seven packages are skipped since they are platform-dependent and +can't be used with Linux. + + +2. Notes for developers using the Debian python packages: + +See the draft of the Debian Python policy in /usr/share/doc/python. + +distutils can be found in the @PVER@-dev package. Development files +like the python library or Makefiles can be found in the @PVER@-dev +package in /usr/lib/@PVER@/config. Therefore, if you need to install +a pure python extension, you only need @PVER@. On the other hand, to +install a C extension, you need @PVER@-dev. + +a) Locally installed Python add-ons + + /usr/local/lib/@PVER@/site-packages/ + /usr/local/lib/site-python/ (version-independent modules) + +b) Python add-ons packaged for Debian + + /usr/lib/@PVER@/site-packages/ + /usr/lib/site-python/ (version-independent modules) + +Note that no package must install files directly into /usr/lib/@PVER@/ +or /usr/local/lib/@PVER@/. Only the site-packages directory is allowed +for third-party extensions. + +Use of the new `package' scheme is strongly encouraged. The `ni' interface +is obsolete in python 1.5. + +Header files for extensions go into /usr/include/@PVER@/. + + +Installing extensions for local use only: +---------------------------------------- + +Consider using distutils ... + +Most extensions use Python's Makefile.pre.in. Note that Makefile.pre.in +by default will install files into /usr/lib/, not into /usr/local/lib/, +which is not allowed for local extensions. You'll have to change the +Makefile accordingly. Most times, "make prefix=/usr/local install" will +work. + + +Packaging python extensions for Debian: +-------------------------------------- + +Maintainers of Python extension packages should read + + /usr/share/doc/python/python-policy.txt.gz + + + + + 03/09/98 + Gregor Hoffleit + +Last change: 2001-12-14 --- python2.7-2.7.15.orig/debian/README.Tk +++ python2.7-2.7.15/debian/README.Tk @@ -0,0 +1,8 @@ +Tkinter documentation can be found at + + http://www.pythonware.com/library/index.htm + +more specific: + + http://www.pythonware.com/library/tkinter/introduction/index.htm + http://www.pythonware.com/library/tkinter/an-introduction-to-tkinter.pdf --- python2.7-2.7.15.orig/debian/README.dbm +++ python2.7-2.7.15/debian/README.dbm @@ -0,0 +1,72 @@ + + Python and dbm modules on Debian + -------------------------------- + +This file documents the configuration of the dbm modules for Debian. It +gives hints at the preferred use of the dbm modules. + + +The preferred way to access dbm databases in Python is the anydbm module. +dbm databases behave like mappings (dictionaries). + +Since there exist several dbm database formats, we choose the following +layout for Python on Debian: + + * creating a new database with anydbm will create a Berkeley DB 2.X Hash + database file. This is the standard format used by libdb starting + with glibc 2.1. + + * opening an existing database with anydbm will try to guess the format + of the file (using whichdb) and then load it using one of the bsddb, + bsddb1, gdbm or dbm (only if the python-gdbm package is installed) + or dumbdbm modules. + + * The modules use the following database formats: + + - bsddb: Berkeley DB 2.X Hash (as in libc6 >=2.1 or libdb2) + - bsddb1: Berkeley DB 1.85 Hash (as in libc6 >=2.1 or libdb2) + - gdbm: GNU dbm 1.x or ndbm + - dbm: " (nearly the same as the gdbm module for us) + - dumbdbm: a hand-crafted format only used in this module + + That means that all usual formats should be readable with anydbm. + + * If you want to create a database in a format different from DB 2.X, + you can still directly use the specified module. + + * I.e. bsddb is the preferred module, and DB 2.X is the preferred format. + + * Note that the db1hash and bsddb1 modules are Debian specific. anydbm + and whichdb have been modified to support DB 2.X Hash files (see + below for details). + + + +For experts only: +---------------- + +Although bsddb employs the new DB 2.X format and uses the new Sleepycat +DB 2 library as included with glibc >= 2.1, it's still using the old +DB 1.85 API (which is still supported by DB 2). + +A more recent version 1.1 of the BSD DB module (available from +http://starship.skyport.net/robind/python/) directly uses the DB 2.X API. +It has a richer set of features. + + +On a glibc 2.1 system, bsddb is linked with -ldb, bsddb1 is linked with +-ldb1 and gdbm as well as dbm are linked with -lgdbm. + +On a glibc 2.0 system (e.g. potato for m68k or slink), bsddb will be +linked with -ldb2 while bsddb1 will be linked with -ldb (therefore +python-base here depends on libdb2). + + +db1hash and bsddb1 nearly completely identical to dbhash and bsddb. The +only difference is that bsddb is linked with the real DB 2 library, while +bsddb1 is linked with an library which provides compatibility with legacy +DB 1.85 databases. + + + July 16, 1999 + Gregor Hoffleit --- python2.7-2.7.15.orig/debian/README.idle-PVER.in +++ python2.7-2.7.15/debian/README.idle-PVER.in @@ -0,0 +1,14 @@ + + The Python IDLE package for Debian + ---------------------------------- + +This package contains Python @VER@'s Integrated DeveLopment Environment, IDLE. + +IDLE is included in the Python @VER@ upstream distribution (Tools/idle) and +depends on Tkinter (available as @PVER@-tk package). + +I have written a simple man page. + + + 06/16/1999 + Gregor Hoffleit --- python2.7-2.7.15.orig/debian/README.maintainers.in +++ python2.7-2.7.15/debian/README.maintainers.in @@ -0,0 +1,88 @@ + +Hints for maintainers of Debian packages of Python extensions +------------------------------------------------------------- + +Most of the content of this README can be found in the Debian Python policy. +See /usr/share/doc/python/python-policy.txt.gz. + +Documentation Tools +------------------- + +If your package ships documentation produced in the Python +documentation format, you can generate it at build-time by +build-depending on @PVER@-dev, and you will find the +templates, tools and scripts in /usr/lib/@PVER@/doc/tools -- +adjust your build scripts accordingly. + + +Makefile.pre.in issues +---------------------- + +Python comes with a `universal Unix Makefile for Python extensions' in +/usr/lib/@PVER@/config/Makefile.pre.in (with Debian, this is included +in the python-dev package), which is used by most Python extensions. + +In general, packages using the Makefile.pre.in approach can be packaged +simply by running dh_make or by using one of debhelper's rules' templates +(see /usr/doc/debhelper/examples/). Makefile.pre.in works fine with e.g. +"make prefix=debian/tmp/usr install". + +One glitch: You may be running into the problem that Makefile.pre.in +doesn't try to create all the directories when they don't exist. Therefore, +you may have to create them manually before "make install". In most cases, +the following should work: + + ... + dh_installdirs /usr/lib/@PVER@ + $(MAKE) prefix=debian/tmp/usr install + ... + + +Byte-compilation +---------------- + +For speed reasons, Python internally compiles source files into a byte-code. +To speed up subsequent imports, it tries to save the byte-code along with +the source with an extension .pyc (resp. pyo). This will fail if the +libraries are installed in a non-writable directory, which may be the +case for /usr/lib/@PVER@/. + +Not that .pyc and .pyo files should not be relocated, since for debugging +purposes the path of the source for is hard-coded into them. + +To precompile files in batches after installation, Python has a script +compileall.py, which compiles all files in a given directory tree. The +Debian version of compileall has been enhanced to support incremental +compilation and to feature a ddir (destination dir) option. ddir is +used to compile files in debian/usr/lib/python/ when they will be +installed into /usr/lib/python/. + + +Currently, there are two ways to use compileall for Debian packages. The +first has a speed penalty, the second has a space penalty in the package. + +1.) Compiling and removing .pyc files in postinst/prerm: + + Use dh_python(1) from the debhelper packages to add commands to byte- + compile on installation and to remove the byte-compiled files on removal. + Your package has to build-depend on: debhelper (>= 4.1.67), python. + + In /usr/share/doc/@PVER@, you'll find sample.postinst and sample.prerm. + If you set the directory where the .py files are installed, these + scripts will install and remove the .pyc and .pyo files for your + package after unpacking resp. before removing the package. + +2.) Compiling the .pyc files `out of place' during installation: + + As of 1.5.1, compileall.py allows you to specify a faked installation + directory using the "-d destdir" option, so that you can precompile + the files in their temporary directory + (e.g. debian/tmp/usr/lib/python2.1/site-packages/PACKAGE). + + + + 11/02/98 + Gregor Hoffleit + + +Last modified: 2007-10-14 --- python2.7-2.7.15.orig/debian/README.python +++ python2.7-2.7.15/debian/README.python @@ -0,0 +1,153 @@ + + Python 2.x for Debian + --------------------- + +This is Python 2.x packaged for Debian. + +This document contains information specific to the Debian packages of +Python 2.x. + + + + [TODO: This document is not yet up-to-date with the packages.] + + + + + + +Currently, it features those two main topics: + + 1. Release notes for the Debian packages: + 2. Notes for developers using the Debian Python packages: + +Release notes and documentation from the upstream package are installed +in /usr/share/doc/python/. + +Up-to-date information regarding Python on Debian systems is also +available as http://www.debian.org/~flight/python/. + +There's a mailing list for discussion of issues related to Python on Debian +systems: debian-python@lists.debian.org. The list is not intended for +general Python problems, but as a forum for maintainers of Python-related +packages and interested third parties. + + + +1. Release notes for the Debian packages: + + +Results of the regression test: +------------------------------ + +The package does successfully run the regression tests for all included +modules. Seven packages are skipped since they are platform-dependent and +can't be used with Linux. + + +Noteworthy changes since the 1.4 packages: +----------------------------------------- + +- Threading support enabled. +- Tkinter for Tcl/Tk 8.x. +- New package python-zlib. +- The dbmmodule was dropped. Use bsddb instead. gdbmmodule is provided + for compatibility's sake. +- python-elisp adheres to the new emacs add-on policy; it now depends + on emacsen. python-elisp probably won't work correctly with emacs19. + Refer to /usr/doc/python-elisp/ for more information. +- Remember that 1.5 has dropped the `ni' interface in favor of a generic + `packages' concept. +- Python 1.5 regression test as additional package python-regrtest. You + don't need to install this package unless you don't trust the + maintainer ;-). +- once again, modified upstream's compileall.py and py_compile.py. + Now they support compilation of optimized byte-code (.pyo) for use + with "python -O", removal of .pyc and .pyo files where the .py source + files are missing (-d) and finally the fake of a installation directory + when .py files have to be compiled out of place for later installation + in a different directory (-i destdir, used in ./debian/rules). +- The Debian packages for python 1.4 do call + /usr/lib/python1.4/compileall.py in their postrm script. Therefore + I had to provide a link from /usr/lib/python1.5/compileall.py, otherwise + the old packages won't be removed completely. THIS IS A SILLY HACK! + + + +2. Notes for developers using the Debian python packages: + + +Embedding python: +---------------- + +The files for embedding python resp. extending the python interpreter +are included in the python-dev package. With the configuration in the +Debian GNU/Linux packages of python 1.5, you will want to use something +like + + -I/usr/include/python1.5 (e.g. for config.h) + -L/usr/lib/python1.5/config -lpython1.5 (... -lpthread) + (also for Makefile.pre.in, Setup etc.) + +Makefile.pre.in automatically gets that right. Note that unlike 1.4, +python 1.5 has only one library, libpython1.5.a. + +Currently, there's no shared version of libpython. Future version of +the Debian python packages will support this. + + +Python extension packages: +------------------------- + +According to www.python.org/doc/essays/packages.html, extension packages +should only install into /usr/lib/python1.5/site-packages/ (resp. +/usr/lib/site-python/ for packages that are definitely version independent). +No extension package should install files directly into /usr/lib/python1.5/. + +But according to the FSSTND, only Debian packages are allowed to use +/usr/lib/python1.5/. Therefore Debian Python additionally by default +searches a second hierarchy in /usr/local/lib/. These directories take +precedence over their equivalents in /usr/lib/. + +a) Locally installed Python add-ons + + /usr/local/lib/python1.5/site-packages/ + /usr/local/lib/site-python/ (version-independent modules) + +b) Python add-ons packaged for Debian + + /usr/lib/python1.5/site-packages/ + /usr/lib/site-python/ (version-independent modules) + +Note that no package must install files directly into /usr/lib/python1.5/ +or /usr/local/lib/python1.5/. Only the site-packages directory is allowed +for third-party extensions. + +Use of the new `package' scheme is strongly encouraged. The `ni' interface +is obsolete in python 1.5. + +Header files for extensions go into /usr/include/python1.5/. + + +Installing extensions for local use only: +---------------------------------------- + +Most extensions use Python's Makefile.pre.in. Note that Makefile.pre.in +by default will install files into /usr/lib/, not into /usr/local/lib/, +which is not allowed for local extensions. You'll have to change the +Makefile accordingly. Most times, "make prefix=/usr/local install" will +work. + + +Packaging python extensions for Debian: +-------------------------------------- + +Maintainers of Python extension packages should read README.maintainers. + + + + + 03/09/98 + Gregor Hoffleit + +Last change: 07/16/1999 --- python2.7-2.7.15.orig/debian/README.source +++ python2.7-2.7.15/debian/README.source @@ -0,0 +1,7 @@ +The source tarball is lacking the files Lib/profile.py and Lib/pstats.py, +which Debian considers to have a license non-suitable for main (the use +of these modules limited to python). + +The package uses quilt to apply / unapply patches. +See /usr/share/doc/quilt/README.source. The series file is generated +during the build. --- python2.7-2.7.15.orig/debian/_sysconfigdata.py +++ python2.7-2.7.15/debian/_sysconfigdata.py @@ -0,0 +1,6 @@ +import sys + +if hasattr(sys, 'gettotalrefcount'): + from _sysconfigdata_d import * +else: + from _sysconfigdata_nd import * --- python2.7-2.7.15.orig/debian/argparse.egg-info +++ python2.7-2.7.15/debian/argparse.egg-info @@ -0,0 +1,8 @@ +Metadata-Version: 1.0 +Name: argparse +Version: 1.2.1 +Summary: Python command-line parsing library +Author: Steven Bethard +Author-email: steven.bethard@gmail.com +License: Python Software Foundation License +Platform: any --- python2.7-2.7.15.orig/debian/changelog +++ python2.7-2.7.15/debian/changelog @@ -0,0 +1,4631 @@ +python2.7 (2.7.15-4ubuntu4) cosmic; urgency=medium + + * Cherrypick in-progress backports to 2.7 branch from 3.6 branch to fix + test_ssl assertions with openssl 1.1.1. Resolves autopkgtest failure + of the 2.7 with openssl 1.1.1. + + -- Dimitri John Ledkov Tue, 02 Oct 2018 23:12:08 +0100 + +python2.7 (2.7.15-4ubuntu3) cosmic; urgency=medium + + * Update to 20180926 from the 2.7 branch. + + -- Matthias Klose Wed, 26 Sep 2018 14:12:25 +0200 + +python2.7 (2.7.15-4ubuntu1) cosmic; urgency=medium + + * Update to 20180907 from the 2.7 branch. + * Ignore the test_ctypes test failure on arm64 in debug mode. Still + needs proper investigation. + + -- Matthias Klose Fri, 07 Sep 2018 11:51:13 +0200 + +python2.7 (2.7.15-4) unstable; urgency=medium + + * Update to 20180831 from the 2.7 branch. + - Fixes the build with OpenSSL 1.1.1. Closes: #900157. + * Don't run the test_ftplib and test_ssl autopkg tests, not yet ready + for OpenSSL 1.1.1. Closes: #907033. + + -- Matthias Klose Fri, 31 Aug 2018 13:56:52 +0200 + +python2.7 (2.7.15-3) unstable; urgency=medium + + * Bump standards version. + * Pass the list of the pyFPE breaks as a parameter into dpkg-gencontrol + instead of hard-coding them in the control file. + + -- Matthias Klose Sat, 28 Jul 2018 13:29:29 +0200 + +python2.7 (2.7.15-1) unstable; urgency=medium + + * Python 2.7.15 release. + + -- Matthias Klose Tue, 01 May 2018 07:55:50 +0200 + +python2.7 (2.7.15~rc1-1) unstable; urgency=medium + + * Python 2.7.15 release candidate 1. + + -- Matthias Klose Sun, 15 Apr 2018 23:51:34 +0200 + +python2.7 (2.7.14-8) unstable; urgency=medium + + * Update to 20180402 from the 2.7 branch. + + -- Matthias Klose Mon, 02 Apr 2018 06:16:25 +0200 + +python2.7 (2.7.14-7) unstable; urgency=medium + + * Update to 20180313 from the 2.7 branch. + - Fix issue #32185: The SSL module no longer sends IP addresses in SNI TLS + extension on platforms with OpenSSL 1.0.2+ or inet_pton. See #892814. + * Add support for riscv64 (Aurelien Jarno). Closes: #892329. + + -- Matthias Klose Tue, 13 Mar 2018 16:23:44 +0100 + +python2.7 (2.7.14-6) unstable; urgency=medium + + * Don't run lib2to3 tests which rely on the pickled grammar files. + + -- Matthias Klose Tue, 06 Feb 2018 20:12:18 +0100 + +python2.7 (2.7.14-5) unstable; urgency=medium + + * Update to 20180204 from the 2.7 branch. + - Fix issue #31530. Closes: #889280. + * python2.7-minimal: Pre-Depend on zlib1g. Closes: #887629. + + -- Matthias Klose Sun, 04 Feb 2018 09:35:17 +0100 + +python2.7 (2.7.14-4) unstable; urgency=medium + + * Fix applying the m-i-p-s-r6 patch. + + -- Matthias Klose Tue, 05 Dec 2017 16:17:02 +0100 + +python2.7 (2.7.14-3) unstable; urgency=medium + + * Update to 20171205 from the 2.7 branch. + * Build with -fstack-protector instead of -fstack-protector-strong. + Performance improvements of around 1-2%. + * Add support for mipsr6 triplets (YunQiang Su). Closes: #881945. + + -- Matthias Klose Tue, 05 Dec 2017 10:01:24 +0100 + +python2.7 (2.7.14-2) unstable; urgency=medium + + * Really rename the md5_* functions. + + -- Matthias Klose Sun, 17 Sep 2017 20:50:44 +0200 + +python2.7 (2.7.14-1) unstable; urgency=medium + + * Python 2.7.14 release. + + -- Matthias Klose Sun, 17 Sep 2017 14:27:46 +0200 + +python2.7 (2.7.14~rc1-3) unstable; urgency=medium + + * Add package breaks for extensions referencing symbols for the removed + _PyFPE module. Closes: #873791, #873915, #873899. + * Expect the regrtest test to fail on s390x. + + -- Matthias Klose Tue, 05 Sep 2017 20:16:23 +0200 + +python2.7 (2.7.14~rc1-2) unstable; urgency=medium + + * Rename md5_* functions to _Py_md5_*. Closes: #868366. + * Break python-numpy (<< 1:1.12.1-3.1), referencing the now missing fpectl + modules. Closes: #873791. + + -- Matthias Klose Thu, 31 Aug 2017 17:34:52 +0200 + +python2.7 (2.7.14~rc1-1) unstable; urgency=medium + + * Python 2.7.14 release candidate 1. + * Stop building the fpectl extension. + * Build the _math.o object file without -fPIC for static builds. LP: #1638695. + + -- Matthias Klose Wed, 30 Aug 2017 12:54:17 +0200 + +python2.7 (2.7.13-4) unstable; urgency=medium + + * Update to 20170719 from the 2.7 branch. + * Move test/support from libpython2.7-testsuite to libpython2.7-stdlib. + Closes: #868168. + + -- Matthias Klose Wed, 19 Jul 2017 20:15:03 +0200 + +python2.7 (2.7.13-3) unstable; urgency=medium + + * Update to 20170608 from the 2.7 branch. + - bpo-27945: Fixed various segfaults with dict when input collections are + mutated during searching, inserting or comparing. + - bpo-25794: Fixed type.__setattr__() and type.__delattr__() for + non-interned or unicode attribute names. + - bpo-29935: Fixed error messages in the index() method of tuple and list + when pass indices of wrong type. + - bpo-28598: Support __rmod__ for subclasses of str being called before + str.__mod__. + - bpo-29602: Fix incorrect handling of signed zeros in complex constructor + for complex subclasses and for inputs having a __complex__ method. + - bpo-29347: Fixed possibly dereferencing undefined pointers + when creating weakref objects. + - Issue #14376: Allow sys.exit to accept longs as well as ints. + - Issue #29028: Fixed possible use-after-free bugs in the subscription + of the buffer object with custom index object. + - Issue #29145: Fix overflow checks in string, bytearray and unicode. + - Issue #28932: Do not include if it does not exist. + - bpo-30378: Fix the problem that logging.handlers.SysLogHandler cannot + handle IPv6 addresses. + - bpo-29960: Preserve generator state when _random.Random.setstate() + raises an exception. + - bpo-30310: tkFont now supports unicode options (e.g. font family). + - bpo-30414: multiprocessing.Queue._feed background running + thread do not break from main loop on exception. + - bpo-30003: Fix handling escape characters in HZ codec. + - bpo-30375: Warnings emitted when compile a regular expression now always + point to the line in the user code. Previously they could point into + inners of the re module if emitted from inside of groups or conditionals. + - bpo-30363: Running Python with the -3 option now warns about regular + expression syntax that is invalid or has different semantic in Python 3 + or will change the behavior in future Python versions. + - bpo-30365: Running Python with the -3 option now emits deprecation + warnings for getchildren() and getiterator() methods of the Element class + in the xml.etree.cElementTree module and when pass the html argument to + xml.etree.ElementTree.XMLParser(). + - bpo-30365: Fixed a deprecation warning about the doctype() method of the + xml.etree.ElementTree.XMLParser class. Now it is emitted only when define + the doctype() method in the subclass of XMLParser. + - bpo-29990: Fix range checking in GB18030 decoder. + - bpo-30243: Removed the __init__ methods of _json's scanner and encoder. + Misusing them could cause memory leaks or crashes. Now scanner and + encoder objects are completely initialized in the __new__ methods. + - Revert bpo-26293 for zipfile breakage. See also bpo-29094. + - bpo-30070: Fixed leaks and crashes in errors handling in the parser + module. + - bpo-30061: Fixed crashes in IOBase methods next() and readlines() when + readline() or next() respectively return non-sizeable object. + Fixed possible other errors caused by not checking results of + PyObject_Size(), PySequence_Size(), or PyMapping_Size(). + - bpo-30011: Fixed race condition in HTMLParser.unescape(). + - bpo-30068: _io._IOBase.readlines will check if it's closed first when + hint is present. + - bpo-27863: Fixed multiple crashes in ElementTree caused by race + conditions and wrong types. + - bpo-29942: Fix a crash in itertools.chain.from_iterable when encountering + long runs of empty iterables. + - bpo-29861: Release references to tasks, their arguments and their results + as soon as they are finished in multiprocessing.Pool. + - bpo-27880: Fixed integer overflow in cPickle when pickle large strings or + too many objects. + - bpo-29110: Fix file object leak in aifc.open() when file is given as a + filesystem path and is not in valid AIFF format. + - Issue #29354: Fixed inspect.getargs() for parameters which are cell + variables. + - Issue #29335: Fix subprocess.Popen.wait() when the child process has + exited to a stopped instead of terminated state (ex: when under ptrace). + - Issue #29219: Fixed infinite recursion in the repr of uninitialized + ctypes.CDLL instances. + - Issue #29188: Support glibc 2.24 on Linux: don't use getentropy() + function but read from /dev/urandom to get random bytes, for example in + os.urandom(). On Linux, getentropy() is implemented which getrandom() + is blocking mode, whereas os.urandom() should not block. + - Issue #29142: In urllib, suffixes in no_proxy environment variable + with leading dots could match related hostnames again (e.g. .b.c + matches a.b.c). + - Issue #13051: Fixed recursion errors in large or resized + curses.textpad.Textbox. + - Issue #9770: curses.ascii predicates now work correctly with negative + integers. + - Issue #28427: old keys should not remove new values from + WeakValueDictionary when collecting from another thread. + - Issue #28998: More APIs now support longs as well as ints. + - Issue 28923: Remove editor artifacts from Tix.py, + including encoding not recognized by codecs.lookup. + - Issue #29019: Fix dict.fromkeys(x) overallocates when x is sparce dict. + - Issue #19542: Fix bugs in WeakValueDictionary.setdefault() and + WeakValueDictionary.pop() when a GC collection happens in another + thread. + - Issue #28925: cPickle now correctly propagates errors when unpickle + instances of old-style classes. + - Issue #26355: Add canonical header link on each page to corresponding + major version of the documentation. + - Issue #12067: Rewrite Comparisons section in the Expressions chapter of + the language reference. Some of the details of comparing mixed types were + incorrect or ambiguous. Added default behaviour and consistency + suggestions for user-defined classes. + - bpo-29243: Prevent unnecessary rebuilding of Python during ``make test``, + ``make install`` and some other make targets when configured with + ``--enable-optimizations``. + - bpo-23404: Don't regenerate generated files based on file modification + time anymore: the action is now explicit. Replace ``make touch`` with + ``make regen-all``. + - bpo-27593: sys.version and the platform module python_build(), + python_branch(), and python_revision() functions now use + git information rather than hg when building from a repo. + - bpo-29643: Fix ``--enable-optimization`` configure option didn't work. + - Issue #28768: Fix implicit declaration of function _setmode. + - bpo-11790: Fix sporadic failures in + test_multiprocessing.WithProcessesTestCondition. + - bpo-30236: Backported test.regrtest options -m/--match and -G/--failfast + from Python 3. + - bpo-30223: To unify running tests in Python 2.7 and Python 3, the test + package can be run as a script. This is equivalent to running the + test.regrtest module as a script. + - bpo-30207: To simplify backports from Python 3, the test.test_support + module was converted into a package and renamed to test.support. The + test.script_helper module was moved into the test.support package. + Names test.test_support and test.script_helper are left as aliases to + test.support and test.support.script_helper. + - bpo-30197: Enhanced function swap_attr() in the test.test_support module. + It now works when delete replaced attribute inside the with statement. + The old value of the attribute (or None if it doesn't exist) now will be + assigned to the target of the "as" clause, if there is one. + Also backported function swap_item(). + - bpo-15083: Convert ElementTree doctests to unittests. + * Explicitly use the system python for byte compilation in postinst scripts. + Addresses: #852163. LP: #1682934. + * Build using -fexceptions on ppc64 and ppc64el. + Closes: #862925. LP: #1691848. + + -- Matthias Klose Thu, 08 Jun 2017 09:45:33 -0700 + +python2.7 (2.7.13-2) unstable; urgency=medium + + * Lower priority of interpreter packages to optional. + + -- Matthias Klose Thu, 19 Jan 2017 15:48:08 +0100 + +python2.7 (2.7.13-1) unstable; urgency=medium + + * Python 2.7.13 release. + - Revert a37cc3d926ec (Issue #5322). Closes: #847791. + * Fix one more broken -gdb.py symlink. Closes: #807513. + + -- Matthias Klose Sun, 18 Dec 2016 21:19:42 +0100 + +python2.7 (2.7.13~rc1-1) unstable; urgency=medium + + * Python 2.7.13 release candidate 1. + - Issue #5322: Fixed setting __new__ to a PyCFunction inside Python code. + - Issue #28847: dumbdbm no longer writes the index file in when it is not + changed and supports reading read-only files. + - Issue #11145: Fixed miscellaneous issues with C-style formatting of types + with custom __oct__ and __hex__. + - Issue #24469: Fixed memory leak caused by int subclasses without + overridden tp_free (e.g. C-inherited Cython classes). + * Pass CXX when configuring and building. Closes: #846326. + * Add profile for libbluetooth-dev build dependency. Closes: #738520. + + -- Matthias Klose Sun, 04 Dec 2016 15:12:39 +0100 + +python2.7 (2.7.12-7) unstable; urgency=medium + + * Update to 20161121 from the 2.7 branch. + - Issue #19398: Extra slash no longer added to sys.path components + in case of empty compile-time PYTHONPATH components. + - Issue #25659: In ctypes, prevent a crash calling the from_buffer() and + from_buffer_copy() methods on abstract classes like Array. + - Issue #28563: Fixed possible DoS and arbitrary code execution when handle + plural form selections in the gettext module. The expression parser now + supports exact syntax supported by GNU gettext. + - Issue #25507: Add back import needed for 2.x encoding warning box. + Add pointer to 'Encoding declaration' in Language Reference. + - Issue #28666: Now test.test_support.rmtree is able to remove unwritable + or unreadable directories. + - Issue #23839: Various caches now are cleared before running every + test file. + - Issue #26359: Rename --with-optimiations to --enable-optimizations. + + -- Matthias Klose Tue, 22 Nov 2016 01:48:54 +0100 + +python2.7 (2.7.12-5) unstable; urgency=medium + + * Update to 20161104 from the 2.7 branch. + - Issue #28387: Fixed possible crash in _io.TextIOWrapper deallocator when + the garbage collector is invoked in other thread. + * Disable some lib2to3 tests relying on the saved pickled grammar files. + + -- Matthias Klose Fri, 04 Nov 2016 18:04:30 +0100 + +python2.7 (2.7.12-4) unstable; urgency=medium + + * Update to 20161103 from the 2.7 branch. + - Issue #21720: Improve exception message when the type of fromlist is + unicode. fromlist parameter of __import__() only accepts str in Python 2 + and this will help to identify the problem especially when the + unicode_literals future import is used. + - Issue #26906: Resolving special methods of uninitialized type now causes + implicit initialization of the type instead of a fail. + - Issue #18287: PyType_Ready() now checks that tp_name is not NULL. + - Issue #24098: Fixed possible crash when AST is changed in process of + compiling it. + - Issue #28350: String constants with null character no longer interned. + - Issue #27942: String constants now interned recursively in tuples and + frozensets. + - Issue #15578: Correctly incref the parent module while importing. + - Issue #26307: The profile-opt build now applies PGO to the built-in + modules. + - Issue #26020: set literal evaluation order did not match documented + behaviour. + - Issue #28449: tarfile.open() with mode "r" or "r:" now tries to open a + tar file with compression before trying to open it without compression. + Otherwise it had 50% chance failed with ignore_zeros=True. + - Issue #25464: Fixed HList.header_exists() in Tix module by adding + a workaround to Tix library bug. + - Issue #28488: shutil.make_archive() no longer adds entry "./" to ZIP + archive. + - Issue #28480: Fix error building _sqlite3 module when multithreading is + disabled. + - Issue #26293: Fixed writing ZIP files that starts not from the start of + the file. Offsets in ZIP file now are relative to the start of the + archive in conforming to the specification. + - Fix possible integer overflows and crashes in the mmap module with + unusual usage patterns. + - Issue #27897: Fixed possible crash in + sqlite3.Connection.create_collation() if pass invalid string-like object + as a name. + - Issue #1703178: Fix the ability to pass the --link-objects option to the + distutils build_ext command. + - Issue #28253: Fixed calendar functions for extreme months: 0001-01 + and 9999-12. + Methods itermonthdays() and itermonthdays2() are reimplemented so + that they don't call itermonthdates() which can cause datetime.date + under/overflow. + - Issue #27963: Fixed possible null pointer dereference in + ctypes.set_conversion_mode(). + - Issue #28284: Strengthen resistance of ``_json.encode_basestring_ascii()`` + to integer overflow. + - Issue #27611: Fixed support of default root window in the Tix module. + - Issue #24363: When parsing HTTP header fields, if an invalid line is + encountered, skip it and continue parsing. Previously, no more header + fields were parsed, which could lead to fields for HTTP framing like + Content-Length and Transfer-Encoding being overlooked. + - Issue #27599: Fixed buffer overrun in binascii.b2a_qp() and + binascii.a2b_qp(). + - Issue #25969: Update the lib2to3 grammar to handle the unpacking + generalizations added in 3.5. + - Issue #24594: Validates persist parameter when opening MSI database + - Issue #27570: Avoid zero-length memcpy() etc calls with null source + pointers in the "ctypes" and "array" modules. + - Issue #22450: urllib now includes an "Accept: */*" header among the + default headers. This makes the results of REST API requests more + consistent and predictable especially when proxy servers are involved. + - lib2to3.pgen3.driver.load_grammar() now creates a stable cache file + between runs given the same Grammar.txt input regardless of the hash + randomization setting. + - Issue #27691: Fix ssl module's parsing of GEN_RID subject alternative + name fields in X.509 certs. + - Issue #27850: Remove 3DES from ssl module's default cipher list to + counter measure sweet32 attack (CVE-2016-2183). + - Issue #27766: Add ChaCha20 Poly1305 to ssl module's default ciper list. + (Required OpenSSL 1.1.0 or LibreSSL). + - Issue #26470: Port ssl and hashlib module to OpenSSL 1.1.0. + Closes: #835793. + - Issue #27944: Fix some memory-corruption bugs in the log reading code + of the _hotshot module. + - Issue #27934: Use ``float.__repr__`` instead of plain ``repr`` when JSON- + encoding an instance of a float subclass. + - Issue #21201: Improves readability of multiprocessing error message. + - Issue #15308: Add 'interrupt execution' (^C) to Shell menu. + - Issue #27922: Stop IDLE tests from 'flashing' gui widgets on the screen. + - Issue #17642: add larger font sizes for classroom projection. + - Add version to title of IDLE help window. + - Issue #25564: In section on IDLE -- console differences, mention that + using exec means that __builtins__ is defined for each statement. + - Issue #28513: Documented command-line interface of zipfile. + - Issue #28258: Fixed build with Estonian locale. + - Issue #26661: setup.py now detects system libffi with multiarch wrapper. + - Issue #15819: The Include directory in the build tree is already + searched; drop unused code trying to add it again. + - Issue #27566: Fix clean target in freeze makefile. + - Issue #27983: Cause lack of llvm-profdata tool when using clang as + required for PGO linking to be a configure time error rather than + make time when --with-optimizations is enabled. Also improve our + ability to find the llvm-profdata tool on MacOS and some Linuxes. + - Issue #26359: Add the --with-optimizations configure flag. + - Issue #27952: Get Tools/scripts/fixcid.py working with the current "re" + module, avoid invalid Python backslash escapes, and fix a bug parsing + escaped C quote signs. + + -- Matthias Klose Thu, 03 Nov 2016 11:11:39 +0100 + +python2.7 (2.7.12-3) unstable; urgency=medium + + * Update to 20160901 from the 2.7 branch. + - Issue #27870: A left shift of zero by a large integer no longer attempts + to allocate large amounts of memory. + - Issue #25604: Fix a minor bug in integer true division; this bug could + potentially have caused off-by-one-ulp results on platforms with + unreliable ldexp implementations. + - Issue #27861: Fixed a crash in sqlite3.Connection.cursor() when a factory + creates not a cursor. + - Issue #10513: Fix a regression in Connection.commit(). Statements should + not be reset after a commit. + - Issue #2466: posixpath.ismount now correctly recognizes mount points which + the user does not have permission to access. + - Issue #27783: Fix possible usage of uninitialized memory in + operator.methodcaller. + - Issue #27774: Fix possible Py_DECREF on unowned object in _sre. + - Issue #27760: Fix possible integer overflow in binascii.b2a_qp. + - In the curses module, raise an error if window.getstr() or window.instr() + is passed a negative value. + - Issue #27758: Fix possible integer overflow in the _csv module for large + record lengths. + - Issue #23369: Fixed possible integer overflow in + _json.encode_basestring_ascii. + - Issue #27714: text_textview and test_autocomplete now pass when re-run + in the same process. This occurs when test_idle fails when run with the + -w option but without -jn. Fix warning from test_config. + - Issue #27452: add line counter and crc to IDLE configHandler test dump. + + -- Matthias Klose Thu, 01 Sep 2016 22:27:38 +0200 + +python2.7 (2.7.12-2) unstable; urgency=medium + + * Update to 20160804 from the 2.7 branch. + - Issue #27473: Fixed possible integer overflow in str, unicode and + bytearray concatenations and repetitions. + - Issue #27507: Add integer overflow check in bytearray.extend(). + - Issue #27581: Don't rely on wrapping for overflow check in + PySequence_Tuple(). + - Issue #23908: os functions, open() and the io.FileIO constructor now + reject unicode paths with embedded null character on Windows instead of + silently truncating them. + - Issue #27514: Make having too many statically nested blocks a SyntaxError + instead of SystemError. + - Issue #27568: Prevent HTTPoxy attack (CVE-2016-1000110). Ignore the + HTTP_PROXY variable when REQUEST_METHOD environment is set, which + indicates that the script is in CGI mode. + - Issue #27130: In the "zlib" module, fix handling of large buffers + (typically 2 or 4 GiB). Previously, inputs were limited to 2 GiB, and + compression and decompression operations did not properly handle results + of 2 or 4 GiB. + - Issue #23804: Fix SSL zero-length recv() calls to not block and not raise + an error about unclean EOF. + - Issue #27466: Change time format returned by http.cookie.time2netscape, + confirming the netscape cookie format and making it consistent with + documentation. + - Issue #22115: Fixed tracing Tkinter variables: trace_vdelete() with wrong + mode no longer break tracing, trace_vinfo() now always returns a list of + pairs of strings. + - Issue #27079: Fixed curses.ascii functions isblank(), iscntrl() and + ispunct(). + - Issue #22636: Avoid shell injection problems with + ctypes.util.find_library(). + - Issue #27330: Fixed possible leaks in the ctypes module. + - Issue #27238: Got rid of bare excepts in the turtle module. + - Issue #26386: Fixed ttk.TreeView selection operations with item id's + containing spaces. + - Issue #25455: Fixed a crash in repr of cElementTree.Element with + recursive tag. + - Issue #27365: Allow non-ascii chars in IDLE NEWS.txt, for contributor + names. + - Issue #27245: IDLE: Cleanly delete custom themes and key bindings. + Previously, when IDLE was started from a console or by import, a cascade + of warnings was emitted. + - Issue #16484: Change the default PYTHONDOCS URL to "https:", and fix the + resulting links to use lowercase. + - Issue #27369: In test_pyexpat, avoid testing an error message detail that + changed in Expat 2.2.0. + * Fix issue 27239, idlelib: macos _tk_type shall always be "other". + Closes: #830686. + * Ignore the winreg module for the set of minimal modules. Closes: #830573. + + -- Matthias Klose Thu, 04 Aug 2016 22:04:34 +0200 + +python2.7 (2.7.12-1) unstable; urgency=medium + + * Python 2.7.12 release. + + -- Matthias Klose Wed, 29 Jun 2016 10:18:26 +0200 + +python2.7 (2.7.12~rc1-2) unstable; urgency=medium + + * Extend debian/copyright to the files shipped in the wheel files. + + -- Matthias Klose Mon, 13 Jun 2016 11:20:59 +0200 + +python2.7 (2.7.12~rc1-1) unstable; urgency=medium + + * Python 2.7.12 release candidate 1. + - Issue #20041: Fixed TypeError when frame.f_trace is set to None. + - Issue #25702: A --with-lto configure option has been added that will + enable link time optimizations at build time during a make profile-opt. + Some compilers and toolchains are known to not produce stable code when + using LTO, be sure to test things thoroughly before relying on it. + It can provide a few % speed up over profile-opt alone. + - Issue #26556: Update expat to 2.1.1, fixes CVE-2015-1283. + - Fix TLS stripping vulnerability in smptlib, CVE-2016-0772. + - Issue #7356: ctypes.util: Make parsing of ldconfig output independent of + the locale. + - Issue #25738: Stop BaseHTTPServer.BaseHTTPRequestHandler.send_error() + from sending a message body for 205 Reset Content. Also, don't send the + Content-Type header field in responses that don't have a body. + - Issue #21313: Fix the "platform" module to tolerate when sys.version + contains truncated build information. + - Issue #27211: Fix possible memory corruption in io.IOBase.readline(). + - Issue #5124: Paste with text selected now replaces the selection on X11. + This matches how paste works on Windows, Mac, most modern Linux apps, + and ttk widgets. + - Issue #24759: Make clear in idlelib.idle_test.__init__ that the directory + is a private implementation of test.test_idle and tool for maintainers. + - Issue #21916: Added tests for the turtle module. + - Issue #27229: Fix the cross-compiling pgen rule for in-tree builds. + - Issue #17500, and https://github.com/python/pythondotorg/issues/945: Remove + unused and outdated icons. + + -- Matthias Klose Mon, 13 Jun 2016 09:07:49 +0200 + +python2.7 (2.7.11-11) unstable; urgency=medium + + * Update to 20160602 from the 2.7 branch. + - Issue #26168: Fixed possible refleaks in failing Py_BuildValue() with + the "N" format unit. + - Issue #27114: Fix SSLContext._load_windows_store_certs fails with + PermissionError. + - Issue #26673: When tk reports font size as 0, change to size 10. + Such fonts on Linux prevented the configuration dialog from opening. + - Issue #27044: Add ConfigDialog.remove_var_callbacks to stop memory leaks. + - In the 'IDLE-console differences' section of the IDLE doc, clarify + how running with IDLE affects sys.modules and the standard streams. + - Issue #25507: Fix incorrect change in IOBinding that prevented printing. + Change also prevented saving shell window with non-ascii characters. + Augment IOBinding htest to include all major IOBinding functions. + - Issue #25905: Revert unwanted conversion of ' to ’ RIGHT SINGLE QUOTATION + MARK in README.txt and open this and NEWS.txt with 'ascii'. + Re-encode CREDITS.txt to utf-8 and open it with 'utf-8'. + * Rebuild to pick up the GNU triplet change on i386 archs. Closes: #826128. + + -- Matthias Klose Thu, 02 Jun 2016 21:34:15 +0200 + +python2.7 (2.7.11-10) unstable; urgency=medium + + * Update to 20160518 from the 2.7 branch. + - Issue #27039: Fixed bytearray.remove() for values greater than 127. + - Issue #14132: Fix urllib.request redirect handling when the target only + has a query string. + - Removed the requirements for the ctypes and modulefinder modules to be + compatible with earlier Python versions. + - Issue #22274: In the subprocess module, allow stderr to be redirected to + stdout even when stdout is not redirected. + - Issue #12045: Avoid duplicate execution of command in + ctypes.util._get_soname(). + - Issue #26960: Backported #16270 from Python 3 to Python 2, to prevent + urllib from hanging when retrieving certain FTP files. + + -- Matthias Klose Wed, 18 May 2016 21:39:41 +0200 + +python2.7 (2.7.11-9) unstable; urgency=medium + + * Update to 20160509 from the 2.7 branch. + - Issue #25745: Fixed leaking a userptr in curses panel destructor. + - Issue #17765: weakref.ref() no longer silently ignores keyword arguments. + - Issue #26873: xmlrpclib now raises ResponseError on unsupported type tags + instead of silently return incorrect result. + - Issue #24114: Fix an uninitialized variable in `ctypes.util`. + - Issue #26864: In urllib, change the proxy bypass host checking against + no_proxy to be case-insensitive, and to not match unrelated host names + that happen to have a bypassed hostname as a suffix. + - Issue #26804: urllib will prefer lower_case proxy environment variables + over UPPER_CASE or Mixed_Case ones. + - Issue #26837: assertSequenceEqual() now correctly outputs non-stringified + differing items. This affects assertListEqual() and assertTupleEqual(). + - Issue #26822: itemgetter, attrgetter and methodcaller objects no longer + silently ignore keyword arguments. + - Issue #26657: Fix directory traversal vulnerability with SimpleHTTPServer + on Windows. This fixes a regression that was introduced in 2.7.7. + - Issue #26736: Used HTTPS for external links in the documentation if + possible. + - Issue #22359: Avoid incorrect recursive $(MAKE), and disable the rules for + running pgen when cross-compiling. + - Issue #26799: Fix python-gdb.py: don't get C types once when the Python + code is loaded, but get C types on demand. The C types can change if + python-gdb.py is loaded before the Python executable. + * Fix issue #26673, runtime error in idle3. LP: #1578927. + + -- Matthias Klose Mon, 09 May 2016 17:54:33 +0200 + +python2.7 (2.7.11-8) unstable; urgency=medium + + * Update to 20160417 from the 2.7 branch. + - Issue #4806: Avoid masking the original TypeError exception when using + star (*) unpacking and the exception was raised from a generator. + - Issue #26659: Make the builtin slice type support cycle collection. + - Issue #26718: super.__init__ no longer leaks memory if called multiple + times. NOTE: A direct call of super.__init__ is not endorsed! + - Issue #13410: Fixed a bug in PyUnicode_Format where it failed to properly + ignore errors from a __int__() method. + - Issue #19377: Add .svg to mimetypes.types_map. + - Issue #13952: Add .csv to mimetypes.types_map. + - Issue #16329: Add .webm to mimetypes.types_map. + - Issue #23735: Handle terminal resizing with Readline 6.3+ by installing + our own SIGWINCH handler. + - Issue #6953: Rework the Readline module documentation to group related + functions together, and add more details such as what underlying Readline + functions and variables are accessed. + * Fix gdb auto-load symlink for the python2.7 binary. LP: #1571198. + + -- Matthias Klose Sun, 17 Apr 2016 16:00:29 +0200 + +python2.7 (2.7.11-7) unstable; urgency=medium + + * Update to 20160330 from the 2.7 branch. + + -- Matthias Klose Wed, 30 Mar 2016 23:00:42 +0200 + +python2.7 (2.7.11-6) unstable; urgency=medium + + * Update to 20160323 from the 2.7 branch. + * Always build _math.o with -fPIC. + + -- Matthias Klose Wed, 23 Mar 2016 12:35:56 +0100 + +python2.7 (2.7.11-5) unstable; urgency=medium + + * Update to 20160319, taken from the 2.7 release branch. + * Update symbols files. + * Don't run test_signal on alpha, hanging on the buildd. + + -- Matthias Klose Sat, 19 Mar 2016 13:14:21 +0100 + +python2.7 (2.7.11-4) unstable; urgency=medium + + * Update to 20160222, taken from the 2.7 release branch. + + -- Matthias Klose Mon, 22 Feb 2016 17:38:42 +0100 + +python2.7 (2.7.11-3) unstable; urgency=medium + + * Revert patches concerning issue #22995. + + -- Matthias Klose Mon, 11 Jan 2016 22:04:40 +0100 + +python2.7 (2.7.11-2) unstable; urgency=medium + + * Disable LTO on ppc64, ppc64el and s390x. + * Don't run the test_signal tests on alpha. + + -- Matthias Klose Wed, 09 Dec 2015 01:29:25 +0100 + +python2.7 (2.7.11-1) unstable; urgency=medium + + * Python 2.7.11 release. + * Don't run the test_cpickle test, causes other tests to fail. + See issue 25698. + * Fix building architecture independent packages only. Closes: #806868. + * Don't ship menu files anymore, just desktop files. + * d/p/fix-sslv3-test.diff: properly handle Ubuntu's openssl having OP_NO_SSLv3 + forced on by default (Marc Deslauriers). + * Update symbols files. + + -- Matthias Klose Mon, 07 Dec 2015 14:27:52 +0100 + +python2.7 (2.7.10-5) unstable; urgency=medium + + * Update to 20151010, taken from the 2.7 release branch. + * Adjust setting DH_COMPAT for dh_movefiles with updated debhelper supporting + globbing of arguments. Closes: #800301. + * pydoc: use the pager command if available. Closes: #799555. + + -- Matthias Klose Sat, 10 Oct 2015 11:11:24 +0200 + +python2.7 (2.7.10-4) unstable; urgency=medium + + * Remove byte-code for _sysconfigdata_d.py in /usr/lib/python2.7. + Closes: #793528. + * Make derivatives builds the same as the parent distro. Closes: #797667. + + -- Matthias Klose Sun, 13 Sep 2015 22:30:50 +0200 + +python2.7 (2.7.10-3) unstable; urgency=medium + + * Revert issue #24134 changes, taken from the branch. + * Add hint to install the idle package when trying to run the turtle demo. + Closes: #788621. + + -- Matthias Klose Wed, 01 Jul 2015 12:54:53 +0200 + +python2.7 (2.7.10-2) unstable; urgency=medium + + * Cherry-pick some changes from the 2.7 branch: + - Issue #24264: Fixed buffer overflow in the imageop module. + - Issue #24115: Update uses of PyObject_IsTrue(), PyObject_Not(), + PyObject_IsInstance(), PyObject_RichCompareBool() and _PyDict_Contains() + to check for and handle errors correctly. + - Issue #22095: Fixed HTTPConnection.set_tunnel with default port. The port + value in the host header was set to "None". + - Issue #4753, backport computed gotos. + * Configure --with-computed-gotos. + * Make the build reproducible (Jérémy Bobbio). Closes: #786978. + - Pass time of latest debian/changelog entry to sphinx via SPHINXOPTS. + - Do not store a timestamps when compressing devhelp. + * Pass DATE and TIME macros matching the current debian/changelog entry + when building getbuildinfo.o. + * Don't run the test_io test on sparc. + + -- Matthias Klose Mon, 01 Jun 2015 18:21:46 +0200 + +python2.7 (2.7.10-1) unstable; urgency=medium + + * Python 2.7.10 release. + + -- Matthias Klose Tue, 26 May 2015 14:47:02 +0200 + +python2.7 (2.7.10~rc1-1) unstable; urgency=medium + + * Python 2.7.10 release candidate 1. + * Re-enable running the tests, re-enable the pgo/lto build. + + -- Matthias Klose Sun, 10 May 2015 23:40:03 +0200 + +python2.7 (2.7.9-5) unstable; urgency=medium + + * Update to 20150507, taken from the 2.7 release branch. + - Issue #24134: assertRaises() and assertRaisesRegexp() checks are not + longer successful if the callable is None. + - Issues #24099, #24100, and #24101: Fix free-after-use bug in heapq's + siftup and siftdown functions. + - Backport collections.deque fixes from Python 3.5. Prevents reentrant + badness during deletion by deferring the decref until the container has + been restored to a consistent state. + - Issue #24125: Saved error's line and column numbers when an error + occured. Fixes python-docutils. Closes: #784270. + - Issue #23842, SystemError in os.minor, os.major. Closes: #782081. + + -- Matthias Klose Wed, 06 May 2015 22:47:05 +0200 + +python2.7 (2.7.9-4) unstable; urgency=medium + + * Fix installation of the optimized interpreter. Closes: #766877. + + -- Matthias Klose Wed, 29 Apr 2015 19:09:39 +0200 + +python2.7 (2.7.9-3) unstable; urgency=medium + + * Update to 20150429, taken from the 2.7 release branch. + - Issue #23629: Fix the default __sizeof__ implementation for + variable-sized objects. + - Issue #21526: Tkinter now supports new boolean type in Tcl 8.5. + - Issue #23838: linecache now clears the cache and returns an empty + result on MemoryError. + - Issue #23742: ntpath.expandvars() no longer loses unbalanced single + quotes. + - Issue #21802: The reader in BufferedRWPair now is closed even when + closing writer failed in BufferedRWPair.close(). + - Issue #23671: string.Template now allows to specify the "self" parameter + as keyword argument. string.Formatter now allows to specify the "self" + and the "format_string" parameters as keyword arguments. + - Issue #21560: An attempt to write a data of wrong type no longer cause + GzipFile corruption. + - Issue #23647: Increase imaplib's MAXLINE to accommodate modern mailbox + sizes. + - Issue #23539: If body is None, http.client.HTTPConnection.request now + sets Content-Length to 0 for PUT, POST, and PATCH headers to avoid + 411 errors from some web servers. + - Issue #23136: _strptime now uniformly handles all days in week 0, + including Dec 30 of previous year. + - Issue #23138: Fixed parsing cookies with absent keys or values in + cookiejar. + - Issue #23051: multiprocessing.Pool methods imap() and imap_unordered() + now handle exceptions raised by an iterator. + - Issue #22928: Disabled HTTP header injections in httplib. + - Issue #23615: Module tarfile now can be reloaded with imp.reload(). + - Issue #23799: Added test.test_support.start_threads() for running and + cleaning up multiple threads. + - Issue #22390: test.regrtest now emits a warning if temporary files or + directories are left after running a test. + - Issue #23583: Added tests for standard IO streams in IDLE. + - Issue #23583: Fixed writing unicode to standard output stream in IDLE. + - Issue #22853: Fixed a deadlock when use multiprocessing.Queue at import + time. + - Issue #23476: In the ssl module, enable OpenSSL's + X509_V_FLAG_TRUSTED_FIRST flag on certificate stores when it is available. + - Issue #23576: Avoid stalling in SSL reads when EOF has been reached + in the SSL layer but the underlying connection hasn't been closed. + - Issue #23504: Added an __all__ to the types module. + - Issue #23367: Fix possible overflows in the unicodedata module. + - Issue #23055: Fixed a buffer overflow in PyUnicode_FromFormatV. + - Issue #23048: Fix jumping out of an infinite while loop in the pdb. + - Issue #23458: On POSIX, the file descriptor kept open by os.urandom() is + now set to non inheritable. + - Issue #22113: struct.pack_into() now supports new buffer protocol (in + particular accepts writable memoryview). + - Issues #814253, #9179: Warnings now are raised when group references and + conditional group references are used in lookbehind assertions in regular + expressions. + - Issue #23215: Multibyte codecs with custom error handlers that ignores + errors consumed too much memory and raised SystemError or MemoryError. + - Issue #5700: io.FileIO() called flush() after closing the file. + flush() was not called in close() if closefd=False. + - Issue #21548: Fix pydoc.synopsis() and pydoc.apropos() on modules with + empty docstrings. + - Issue #22885: Fixed arbitrary code execution vulnerability in the dumbdbm + module. + - Issue #23481: Remove RC4 from the SSL module's default cipher list. + - Issue #21849: Fixed xmlrpclib serialization of non-ASCII unicode strings + in the multiprocessing module. + - Issue #21840: Fixed expanding unicode variables of form $var in + posixpath.expandvars(). Fixed all os.path implementations on + unicode-disabled builds. + - Issue #23363: Fix possible overflow in itertools.permutations. + - Issue #23364: Fix possible overflow in itertools.product. + - Issue #23365: Fixed possible integer overflow in + itertools.combinations_with_replacement. + - Issue #23366: Fixed possible integer overflow in itertools.combinations. + - Issue #23191: fnmatch functions that use caching are now threadsafe. + - Issue #18518: timeit now rejects statements which can't be compiled + outside a function or a loop (e.g. "return" or "break"). + - Issue #19996: Make :mod:`httplib` ignore headers with no name rather than + assuming the body has started. + - Issue #20188: Support Application-Layer Protocol Negotiation (ALPN) in the + ssl module. + - Issue #23248: Update ssl error codes from latest OpenSSL git master. + - Issue #23098: 64-bit dev_t is now supported in the os module. + - Issue #23063: In the disutils' check command, fix parsing of reST with + code or code-block directives. + - Issue #21356: Make ssl.RAND_egd() optional to support LibreSSL. The + availability of the function is checked during the compilation. + - Backport the context argument to ftplib.FTP_TLS. + - Issue #23111: Maximize compatibility in protocol versions of + ftplib.FTP_TLS. + - Issue #23112: Fix SimpleHTTPServer to correctly carry the query string + and fragment when it redirects to add a trailing slash. + - Issue #22585: On OpenBSD 5.6 and newer, os.urandom() now calls + getentropy(), instead of reading /dev/urandom, to get pseudo-random bytes. + - Issue #23093: In the io, module allow more operations to work on detached + streams. + - Issue #23071: Added missing names to codecs.__all__. + - Issue #23016: A warning no longer produces an AttributeError when + sys.stderr is None. + - Issue #21032. Fixed socket leak if HTTPConnection.getresponse() fails. + Original patch by Martin Panter. + - Issue #22609: Constructors and update methods of mapping classes in the + collections module now accept the self keyword argument. + - Issue #23006: Improve the documentation and indexing of dict.__missing__. + Add an entry in the language datamodel special methods section. + Revise and index its discussion in the stdtypes mapping/dict section. + Backport the code example from 3.4. + - Issue #21514: The documentation of the json module now refers to new + JSON RFC 7159 instead of obsoleted RFC 4627. + - Issue #6639: Module-level turtle functions no longer raise TclError after + closing the window. + - Issue #22314: pydoc now works when the LINES environment variable is set. + - Issue #18905: "pydoc -p 0" now outputs actually used port. + - Issue #23345: Prevent test_ssl failures with large OpenSSL patch level + values (like 0.9.8zc). + - Issue #23392: Added tests for marshal C API that works with FILE*. + - Issue #18982: Add tests for CLI of the calendar module. + - Issue #19949: The test_xpickle test now tests compatibility with installed + Python 2.7 and reports skipped tests. + - Issue #11578: Backported test for the timeit module. + - Issue #22943: bsddb tests are locale independend now. + - Issue #20577: Configuration of the max line length for the FormatParagraph + extension has been moved from the General tab of the Idle preferences + dialog to the FormatParagraph tab of the Config Extensions dialog. + - Issue #16893: Update Idle doc chapter to match current Idle and add new + information. + - Issue #23180: Rename IDLE "Windows" menu item to "Window". + - Issue #15506: Use standard PKG_PROG_PKG_CONFIG autoconf macro in the + configure script. + - Issue #22079: PyType_Ready() now checks that statically allocated type has + no dynamically allocated bases. + * Re-apply the fix for issue #22079. This is now a warning instead of an + error. LP: #1426294. + * Fix issue #23842, SystemError in os.minor, os.major. LP: #1435242. + * When using GCC versions older than 4.9 for extension builds, automagically + mangle -fstack-protector-strong to -fstack-protector. + * debian/tests: Use init system agnostic "service" command instead of + upstart specific "stop". Also drop unnecessary "status" call right after + stopping apport. + * Refresh patches. + + -- Matthias Klose Wed, 29 Apr 2015 03:03:55 +0200 + +python2.7 (2.7.9-2) unstable; urgency=medium + + * python2.7-minimal: Make Pre-Depends mangling more robust. Closes: #779294. + * python2.7-doc: Depend on libjs-underscore. LP: #1424538. + * Remove LTO sections from the static libraries. Closes: #698395. + + -- Matthias Klose Sun, 01 Mar 2015 10:56:57 +0100 + +python2.7 (2.7.9-1) unstable; urgency=medium + + * Python 2.7.9 release. + + -- Matthias Klose Thu, 11 Dec 2014 00:38:09 +0100 + +python2.7 (2.7.9~rc1-2) unstable; urgency=medium + + * Update to 20141209, taken from the 2.7 release repository. + - Issue #22959: Remove the *check_hostname* parameter of + httplib.HTTPSConnection. The *context* parameter should be used instead. + - Issue #16043: Add a default limit for the amount of data + xmlrpclib.gzip_decode will return. This resolves CVE-2013-1753. + Closes: #742929. + - Issue #16042: CVE-2013-1752: smtplib: Limit amount of data read by + limiting the call to readline(). Closes: #742929. + - Issue #16041: In poplib, limit maximum line length read from the server + to prevent CVE-2013-1752. Closes: #742929. + - Issue #22960: Add a context argument to xmlrpclib.ServerProxy. + - Issue #22935: Allow the ssl module to be compiled if openssl + doesn't support SSL 3. + * Add locales to autopkg test dependencies as in 3.4. + * Remove Demo/scripts/newslist.* from the examples package, not + distributable, will get removed in 2.7.9~rc2 sources. See issue #12987. + * Let ensurepip always use a temporary directory for installations. + + -- Matthias Klose Tue, 09 Dec 2014 15:47:40 +0100 + +python2.7 (2.7.9~rc1-1) unstable; urgency=medium + + * Python 2.7.9 release candidate 1. + - Testsuite updates. + - Issue #16056: Rename test methods to avoid conflict. + - Issue #20351: Add examples for csv.DictReader and csv.DictWriter. + - PEP 476: verify certificates by default (#22417). + - Give urllib.urlopen a context parameter (closes #22927). + - Allow hostname to be passed to SSLContext even if OpenSSL doesn't + support SNI (closes #22921). + - Allow passing cert/ssl information to urllib2.urlopen and + httplib.HTTPSConnection (backport of issues #9003 and #22366). + * Let libpython2.7-stdlib break python-urllib3 (<< 1.9.1-3). Closes: #770157. + * Ignore the test_threading_local test failure in the Debian CI environment. + Succeeds even there when repeated. + * Don't pass default compiler search directories in the pkgconfig file. + Closes: #770935. + + -- Matthias Klose Wed, 26 Nov 2014 21:01:48 +0100 + +python2.7 (2.7.8-12) unstable; urgency=medium + + * Update to 20141118, taken from the 2.7 branch. + - Issue #12728: Different Unicode characters having the same uppercase + but different lowercase are now matched in case-insensitive regular + expressions. + - Issue #22821: Fixed fcntl() with integer argument on 64-bit big-endian + platforms. + - Issues #814253, #9179: Group references and conditional group references + now work in lookbehind assertions in regular expressions. + - Issue #22769: Fixed ttk.Treeview.tag_has() when called without arguments. + - Issue #22787: Allow the keyfile argument of SSLContext.load_cert_chain + to be None. + - Issue #22775: Fixed unpickling of Cookie.SimpleCookie with protocol 2. + - Issue #22776: Brought excluded code into the scope of a try block in + SysLogHandler.emit(). + - Issue #17381: Fixed ranges handling in case-insensitive regular + expressions. + - Issue #19329: Optimized compiling charsets in regular expressions. + - Issue #22410: Module level functions in the re module now cache compiled + locale-dependent regular expressions taking into account the locale. + - Issue #8876: distutils now falls back to copying files when hard linking + doesn't work. This allows use with special filesystems such as + VirtualBox shared folders. + - Issue #22193: Fixed integer overflow error in sys.getsizeof(). + * Backport the ensurepip patch from 3.4. + * Disable ensurepip in Debian, at least for the upcoming release. + * Fix maintainer scripts for byte-code removal. Closes: #769078. + * Allow building and testing without SSLv3 support (Kurt Roeckx). + Closes: #768611. + * Let distutils.sysconfig.get_python_inc() honor the "prefix" argument. + Closes: #769720. + + -- Matthias Klose Tue, 18 Nov 2014 11:37:13 +0100 + +python2.7 (2.7.8-11) unstable; urgency=medium + + * Update to 20141018, taken from the 2.7 branch. + - Issue #9351: Defaults set with set_defaults on an argparse subparser + are no longer ignored when also set on the parent parser. + - Issue #20421: Add a .version() method to SSL sockets exposing the actual + protocol version in use. + - Issue #22435: Fix a file descriptor leak when SocketServer bind fails. + - Issue #13664: GzipFile now supports non-ascii Unicode filenames. + - Issue #13096: Fixed segfault in CTypes POINTER handling of large + values. + - Issue #11694: Raise ConversionError in xdrlib as documented. + - Issue #10712: 2to3 has a new "asserts" fixer that replaces deprecated names + of unittest methods (e.g. failUnlessEqual -> assertEqual). + * Pass -ffat-lto-objects for LTO enabled builds with GCC 4.9. + + -- Matthias Klose Sat, 18 Oct 2014 14:14:19 +0200 + +python2.7 (2.7.8-10) unstable; urgency=medium + + * Update to 20141007, taken from the 2.7 branch. + + -- Matthias Klose Tue, 07 Oct 2014 19:42:51 +0200 + +python2.7 (2.7.8-9) unstable; urgency=medium + + * Fix refcounting error in the fix for issue #22523. Closes: #762010. + + -- Matthias Klose Thu, 02 Oct 2014 13:49:07 +0200 + +python2.7 (2.7.8-8) unstable; urgency=medium + + * Update to 20141002, taken from the 2.7 branch. + * Refresh patches. + * Apply proposed patch for issue #22523. Closes: #762010. + + -- Matthias Klose Thu, 02 Oct 2014 02:13:37 +0200 + +python2.7 (2.7.8-7) unstable; urgency=medium + + * Update to 20140909, taken from the 2.7 branch. + * debian/tests/testsuite{,-dbg}: Several tests fail with configured proxy + and disabled network test resources. Explicitly unset proxy variables. + See issue #22371. + + -- Matthias Klose Tue, 09 Sep 2014 22:02:11 +0200 + +python2.7 (2.7.8-6) unstable; urgency=medium + + * distuils: For extension builds, always pass BASECFLAGS. + + -- Matthias Klose Sat, 23 Aug 2014 22:50:19 +0200 + +python2.7 (2.7.8-5) unstable; urgency=medium + + * Build-depend on dpkg-dev (>= 1.17.11). + + -- Matthias Klose Mon, 18 Aug 2014 09:43:43 +0200 + +python2.7 (2.7.8-4) unstable; urgency=medium + + * distutils: For extension builds pass the CPPFLAGS, CFLAGS, LDFLAGS + used for the python build when these flags cannot be found in the + environment. + * Don't use the system python during the build. + * Build using autotools-dev. Closes: #756772. + * Pass AR and RANLIB for lto enabled builds. + + -- Matthias Klose Sun, 10 Aug 2014 13:45:31 +0200 + +python2.7 (2.7.8-3) unstable; urgency=medium + + * Call dpkg -L in the maintainer scripts with an architecture qualifier + for M-A: same packages. Closes: #736385. + * Apply the plat-linux2_mips patch for mips64 and mips64el. Closes: #755578. + + -- Matthias Klose Sat, 26 Jul 2014 15:32:47 +0200 + +python2.7 (2.7.8-2) unstable; urgency=medium + + * Revert the backport of issue #1856 (avoid daemon thread problems + at shutdown). Issue #21963. Apparently ceph has issues with it. + Closes: #754341. + + -- Matthias Klose Sat, 12 Jul 2014 10:19:55 +0200 + +python2.7 (2.7.8-1) unstable; urgency=medium + + * Python 2.7.8 release. + + -- Matthias Klose Fri, 04 Jul 2014 14:41:31 +0200 + +python2.7 (2.7.7-2) unstable; urgency=medium + + * Re-enable the test_pydoc, test_tools, test_subprocess and test_uuid + autopkg tests. + * In the autopkg tests, make $ADTTMP accessible to the su user. + + -- Matthias Klose Tue, 03 Jun 2014 10:13:57 +0200 + +python2.7 (2.7.7-1) unstable; urgency=medium + + * Python 2.7.7 release. + * Refresh patches. + * In the autopkg tests, set HOME to the temporary home directory after + the su call. + * Expect test failures in the distutils autopkg tests. + * Disable the test_solaris_enable_shared test. + + -- Matthias Klose Mon, 02 Jun 2014 10:53:46 +0200 + +python2.7 (2.7.7~rc1-1) unstable; urgency=medium + + * Python 2.7.7 release candidate 1. + * Run the testsuite in a temporary home directory. + + -- Matthias Klose Wed, 21 May 2014 12:15:26 +0100 + +python2.7 (2.7.6-8) unstable; urgency=medium + + * Set a temporary home directory for the build and the autopkg tests. + + -- Matthias Klose Sat, 22 Mar 2014 14:31:54 +0100 + +python2.7 (2.7.6-8) unstable; urgency=medium + + * Update to 20140322, taken from the 2.7 branch. + * Install updated idle icons. LP: #1295969. + * Update the ssl.match_hostname backport: Change behavior of + ``ssl.match_hostname()`` to follow RFC 6125, for security reasons. + It now doesn't match multiple wildcards nor wildcards inside IDN fragments. + Closes: #740255. + + -- Matthias Klose Sat, 22 Mar 2014 14:31:54 +0100 + +python2.7 (2.7.6-7) unstable; urgency=medium + + * Include test data for test_imghdr test. + + -- Matthias Klose Wed, 26 Feb 2014 01:16:47 +0100 + +python2.7 (2.7.6-6) unstable; urgency=high + + * Update to 20140225, taken from the 2.7 branch. + - CVE-2014-1912. Fix issue 20246, buffer overflow in socket.recvfrom_into. + * Build without ffi on or1k. Closes: #738519. + * Allow loading of extensions in the sqlite module. Closes: #739555. + * Update autopkg tests (Martin Pitt): + - Don't fail if apport is not installed. + - Call su with explicit shell, as nobody has nologin as default shell now. + - Only use $SUDO_USER if that user actually exists in the testbed. + - Drop obsolete chowning of $TMPDIR and $ADTTMP; with current autopkgtest + $TMPDIR has appropriate permissions, and $ADTTMP is not being used. + + -- Matthias Klose Tue, 25 Feb 2014 10:51:27 +0100 + +python2.7 (2.7.6-5) unstable; urgency=medium + + * Update to 20140111, taken from the 2.7 branch. + * Build-depend on net-tools, required for the test_uuid test. + * Build-depend on the default Tcl/Tk. + * Add two new autopkg tests to run the failing tests. + + -- Matthias Klose Sat, 11 Jan 2014 14:52:11 +0100 + +python2.7 (2.7.6-4) unstable; urgency=medium + + * Update to 20131230, taken from the 2.7 branch. + * Disable sphinx refcounting extension, removed in sphinx-1.2. + Closes: #733404. + + -- Matthias Klose Mon, 30 Dec 2013 15:17:09 +0100 + +python2.7 (2.7.6-3) unstable; urgency=low + + * Update to 20131206, taken from the 2.7 branch. + * Disable the test_uuid autopkg test, hanging, missing entropy? + * Drop python dependency in libpython2.7-dbg. + * Revert patch from http://bugs.python.org/issue19352 as it completely breaks + unittest discovery on Debian/Ubuntu. LP: #1255505. + + -- Matthias Klose Fri, 06 Dec 2013 20:35:22 +0100 + +python2.7 (2.7.6-2) unstable; urgency=low + + * Update to 20131121, taken from the 2.7 branch. + * Fix test support when the running kernel doesn't handle port reuse. + * Build-depend on libdb-dev (<< 1:6.0) instead of a specific db version. + + -- Matthias Klose Fri, 22 Nov 2013 13:06:15 +0100 + +python2.7 (2.7.6-1) unstable; urgency=low + + * Python 2.7.6 release. + * Update to 20131119, taken from the 2.7 branch. + * For autopkg tests, only run the separate tests when defined. + * Don't run the curses autopkg test. + * Disable running the testsuite on mipsn32(el) and mips64(el), + requested by YunQiang Su. Closes: #719057. + + -- Matthias Klose Tue, 19 Nov 2013 11:45:31 +0100 + +python2.7 (2.7.5-8) unstable; urgency=medium + + * Update to 20130917, taken from the 2.7 branch. + - Fix SSL module to handle NULL bytes inside subjectAltNames general + names (CVE-2013-4238). Closes: #719566. + * Don't run the curses autopkg test. + * Set Multi-Arch attributes for binary packages. + * Fix multiarch include header for sparc64. Closes: #714802, #715063. + + -- Matthias Klose Tue, 17 Sep 2013 15:47:45 +0200 + +python2.7 (2.7.5-7) unstable; urgency=low + + * Update to 20130803, taken from the 2.7 branch. + * Update package descriptions (Filipus Klutiero). Closes: #715801. + * Fix multiarch include header for sparc64. Closes: #715063. + * Move removal of the sitecustomize.py file into the libpython-minimal + postrm. Closes: #709964. + + -- Matthias Klose Sun, 04 Aug 2013 11:56:52 +0200 + +python2.7 (2.7.5-6) unstable; urgency=low + + * Update to 20130613, taken from the 2.7 branch. + * Refresh patches. + * Don't run consistency check for cross builds. + * Really skip byte compile of non-existing sitecustomize.py. + * Fix the multiarch header file for mips64 (YunQiang Su). Closes: #710374. + + -- Matthias Klose Thu, 13 Jun 2013 13:06:51 +0200 + +python2.7 (2.7.5-5) unstable; urgency=low + + * Update to 20130602, taken from the 2.7 branch. + * Fix possible abuse of ssl.match_hostname() for denial of service + using certificates with many wildcards (CVE-2013-2099). Closes: #709066. + * Don't try to byte-compile sitecustomize.py if the target of the + symlink doesn't exist anymore. Closes: #709157. + * Handle byte compilation in python2.7{-minimal,}, byte removal in + libpython2.7{-minimal,-stdlib}. Closes: #709964. + * Backport patch to fix issue #13146, possible race conditions when writing + .pyc/.pyo files in py_compile.py (Barry Warsaw). LP: #1058884. + * Fix issue #17988, internal error in regular expression engine on 32bit + targets (closes: #710315). + + -- Matthias Klose Sun, 02 Jun 2013 15:11:19 +0200 + +python2.7 (2.7.5-4) unstable; urgency=low + + * Move the libc dependency of -minimal from Depends to Pre-Depends. + Closes: #708831. + * Disable the test_io test on armel, armhf, mips, mipsel. Hangs the + buildds. + + -- Matthias Klose Mon, 20 May 2013 12:21:06 +0200 + +python2.7 (2.7.5-3) unstable; urgency=high + + * Fix the multiarch header file for ppc64. Closes: #708641. + + -- Matthias Klose Sat, 18 May 2013 20:18:38 +0200 + +python2.7 (2.7.5-2) unstable; urgency=low + + * Only run the _multiprocessing build check on linux targets. + + -- Matthias Klose Wed, 15 May 2013 22:09:30 +0200 + +python2.7 (2.7.5-1) unstable; urgency=low + + * Python 2.7.5 release. + * Set the platinclude dir back to the non-multiarch include path, + where the multiarch pyconfig.h compatibility header is found. + * Fix issue #17703: Fix a regression where an illegal use of Py_DECREF() + after interpreter finalization can cause a crash. + * Issue #17754, setting LANG and LC_ALL for the compiler call in ctypes/util. + * Issue #17761, platform._parse_release_file doesn't close the + /etc/lsb-release file, and doesn't know about 'Ubuntu'. + * Fix autopkg tests. + * Re-enable lto and pgo optimized builds, accidentally disabled for the + last upload. + * more autopkg test fixes. + * Link the ctypes extension with the shared libffi library. + * Fix a distutils test with the deb install layout. + * Move lib2to3 library into libpython2.7-stdlib. Closes: #705078. + * Don't set yet any Multi-Arch: attributes in Debian. + + -- Matthias Klose Wed, 15 May 2013 15:02:13 +0200 + +python2.7 (2.7.4-2) experimental; urgency=low + + * Idle updates: + - Issue #17657: Show full Tk version in IDLE's about dialog. + - Issue #17613: Prevent traceback when removing syntax colorizer. + - Issue #1207589: Backwards-compatibility patch for right-click menu. + - Issue #16887: Now accepts Cancel in tabify/untabify dialog box. + - Issue #14254: Now handles readline correctly across shell restarts. + - Issue #17614: No longer raises exception when quickly closing a file. + - Issue #6698: Now opens just an editor window when configured to do so. + - Issue #8900: Using keyboard shortcuts in IDLE to open a file no longer + raises an exception. + - Issue #6649: Fixed missing exit status. + * Build a libpython2.7-testsuite package. LP: #301629. + * Add autopkg tests to run the installed testsuite in normal and debug + mode. + * Re-enable running the tests during the build. + * Add the io and _io modules to libpython2.7-minimal. + * Backport ssl.CertificateError as well. Closes: #626539. LP: #1166344. + * Don't ship an uncompress python man page. Closes: #705079. + + -- Matthias Klose Thu, 11 Apr 2013 00:44:48 +0200 + +python2.7 (2.7.4-1ubuntu4) raring; urgency=low + + * Build a libpython2.7-testsuite package. LP: #301629. + * Add autopkg tests to run the installed testsuite in normal and debug + mode. + * Re-enable running the tests during the build. + * Idle updates: + - Issue #17657: Show full Tk version in IDLE's about dialog. + - Issue #17613: Prevent traceback when removing syntax colorizer. + - Issue #1207589: Backwards-compatibility patch for right-click menu. + - Issue #16887: Now accepts Cancel in tabify/untabify dialog box. + - Issue #14254: Now handles readline correctly across shell restarts. + - Issue #17614: No longer raises exception when quickly closing a file. + - Issue #6698: Now opens just an editor window when configured to do so. + - Issue #8900: Using keyboard shortcuts in IDLE to open a file no longer + raises an exception. + - Issue #6649: Fixed missing exit status. + + -- Matthias Klose Tue, 09 Apr 2013 17:53:02 +0200 + +python2.7 (2.7.4-1ubuntu3) raring; urgency=low + + * Add the io and _io modules to libpython2.7-minimal. LP: #1165172. + * Add missing import for the ssl module. LP: #1166644. + + -- Matthias Klose Tue, 09 Apr 2013 12:11:12 +0200 + +python2.7 (2.7.4-1ubuntu2) raring; urgency=low + + * Backport ssl.CertificateError as well. Closes: #626539. LP: #1166344. + + -- Matthias Klose Mon, 08 Apr 2013 20:59:52 +0200 + +python2.7 (2.7.4-1ubuntu1) raring; urgency=low + + * Merge with Debian; remaining changes: + - Build-depend on python:any instead of python. + + -- Matthias Klose Sat, 06 Apr 2013 17:45:49 +0200 + +python2.7 (2.7.4-1) experimental; urgency=low + + * Python 2.7.4 release. + - Issue #17550: Fix the --enable-profiling configure switch. + - Issue #15801 (again): With string % formatting, relax the type check + for a mapping such that any type with a __getitem__ can be used on the + right hand side. + - Issue #17625: In IDLE, close the replace dialog after it is used. + - Issue #17531: Fix tests that thought group and user ids were always + the int type. Also, always allow -1 as a valid group and user id. + - Issue 17538: Document XML vulnerabilties + * Byte-compile files in libpython2.7-dbg. + * libpython2.7-minimal: Break earlier python2.7-minimal versions. + Closes: #704084. LP: #1157687. + * Call python with -E -S for the byte compilation. + + -- Matthias Klose Sat, 06 Apr 2013 16:38:57 +0200 + +python2.7 (2.7.4~rc1-4) experimental; urgency=low + + * Fix byte-compiliation/-removal for the split-out library packages. + LP: #1160944. + + -- Matthias Klose Sat, 30 Mar 2013 12:51:58 +0100 + +python2.7 (2.7.4~rc1-3) experimental; urgency=low + + * Fix webbrowser update. Closes: #703872. LP: #1159636. + + -- Matthias Klose Mon, 25 Mar 2013 14:33:50 +0100 + +python2.7 (2.7.4~rc1-2) experimental; urgency=low + + * Backport webbrowser updates from 3.3. Closes: #700429. + * Build again using db-5.1 instead of db-5.3. + + -- Matthias Klose Sun, 24 Mar 2013 18:27:57 +0100 + +python2.7 (2.7.4~rc1-1) experimental; urgency=low + + * Python 2.7.4 release candidate 1. + - Issue #10211: Buffer objects expose the new buffer interface internally. + - Issue #10212: cStringIO and struct.unpack support new buffer objects. + - Issue #12098: multiprocessing on Windows now starts child processes + using the same sys.flags as the current process. + - Issue #8862: Fixed curses cleanup when getkey is interrputed by a signal. + - Issue #9090: When a socket with a timeout fails with EWOULDBLOCK or + EAGAIN, retry the select() loop instead of bailing out. + - Issue #1285086: Get rid of the refcounting hack and speed up + urllib.unquote(). + - Issue #17368: Fix an off-by-one error in the Python JSON decoder + that caused a failure while decoding empty object literals when + object_pairs_hook was specified. + - Issue #17477: Update the bsddb module to pybsddb 5.3.0, supporting + db-5.x, and dropping support for db-4.1 and db-4.2. + - Issue #17192: Update the ctypes module's libffi to v3.0.13. This + specifically addresses a stack misalignment issue on x86 and issues on + some more recent platforms. + - Issue #11420: make test suite pass with -B/DONTWRITEBYTECODE set. + - Issue #17299: Add test coverage for cPickle with file objects + and general IO objects. + - Issue #11963: remove human verification from test_parser and + test_subprocess. + - Issue #16004: Add `make touch`. + - Issue #17047: remove doubled words in docs and docstrings + * Rework the sysconfigdata patch into something upstreamable. + + -- Matthias Klose Sun, 24 Mar 2013 01:56:36 +0100 + +python2.7 (2.7.3-16ubuntu2) raring; urgency=low + + * Update to 20130315, taken from the 2.7 branch. + - Issue #1285086: Get rid of the refcounting hack and speed + up urllib.unquote(). + - Issue #17368: Fix an off-by-one error in the Python JSON decoder + that caused a failure while decoding empty object literals when + object_pairs_hook was specified. + - Issue #17299: Add test coverage for cPickle with file objects and general + IO objects. + - Issue #11963: Remove human verification from test_parser and + test_subprocess. + - Issue #16004: Add `make touch`. + - Issue #17412: Update 2.7 Doc/make.bat to also use sphinx-1.0.7. + - Issue #17047: Remove doubled words in docs and docstrings. + * Revert the patch for Issue #1159051, handling corrupted gzip files + with unexpected EOF. LP: #1116079. + + -- Matthias Klose Fri, 15 Mar 2013 12:20:10 -0700 + +python2.7 (2.7.3-16ubuntu1) raring; urgency=low + + * Merge with Debian; remaining changes: + - Build-depend on python:any instead of python. + * Update symbols files. + + -- Matthias Klose Fri, 08 Mar 2013 14:30:55 +0800 + +python2.7 (2.7.3-16) experimental; urgency=low + + * Update to 20130308, taken from the 2.7 branch. + - Issue #10156: In the interpreter's initialization phase, unicode globals + are now initialized dynamically as needed. + - Issue #16975: Fix error handling bug in the escape-decode decoder. + - Issue #9290: In IDLE the sys.std* streams now implement io.TextIOBase + interface and support all mandatory methods and properties. + - Issue #13454: Fix a crash when deleting an iterator created by + itertools.tee() if all other iterators were very advanced before. + - Issue #3754: fix typo in pthread AC_CACHE_VAL. + - Issue #17029: Let h2py search the multiarch system include directory. + - Issue #16445: Fixed potential segmentation fault when deleting an + exception message. + - Issue #17275: Corrected class name in init error messages of the + C version of BufferedWriter and BufferedRandom. + - Issue #7963: Fixed misleading error message that issued when object is + called without arguments. + - Issue #5308: Raise ValueError when marshalling too large object (a + sequence with size >= 2**31), instead of producing illegal marshal data. + - Issue #17043: The unicode-internal decoder no longer read past the end of + input buffer. + - Issue #16979: Fix error handling bugs in the unicode-escape-decode + decoder. + - Issue #17278: Fix a crash in heapq.heappush() and heapq.heappop() when + the list is being resized concurrently. + - Issue #17018: Make Process.join() retry if os.waitpid() fails with EINTR. + - Issue #14720: sqlite3: Convert datetime microseconds correctly. + - Issue #17225: JSON decoder now counts columns in the first line starting + with 1, as in other lines. + - Issue #7842: backported fix for py_compile.compile() syntax error + handling. + - Issue #13153: Tkinter functions now raise TclError instead of ValueError + when a unicode argument contains non-BMP character. + - Issue #9669: Protect re against infinite loops on zero-width matching in + non-greedy repeat. + - Issue #13169: The maximal repetition number in a regular expression + has been increased from 65534 to 2147483647 (on 32-bit platform) or + 4294967294 (on 64-bit). + - Issue #11311: StringIO.readline(0) now returns an empty string + as all other file-like objects. + - Issue #16800: tempfile.gettempdir() no longer left temporary files when + the disk is full. Original patch by Amir Szekely. + - Issue #13555: cPickle now supports files larger than 2 GiB. + - Issue #17052: unittest discovery should use self.testLoader. + - Issue #4591: Uid and gid values larger than 2**31 are supported now. + - Issue #17141: random.vonmisesvariate() no more hangs for large kappas. + - Issue #17149: Fix random.vonmisesvariate to always return results in + the range [0, 2*math.pi]. + - Issue #1470548: XMLGenerator now works with UTF-16 and UTF-32 encodings. + - Issue #6975: os.path.realpath() now correctly resolves multiple nested + symlinks on POSIX platforms. + - Issue #17156: pygettext.py now correctly escapes non-ascii characters. + - Issue #7358: cStringIO.StringIO now supports writing to and reading from + a stream larger than 2 GiB on 64-bit systems. + - IDLE was displaying spurious SystemExit tracebacks when running scripts + that terminated by raising SystemExit (i.e. unittest and turtledemo). + - Issue #10355: In SpooledTemporaryFile class mode and name properties and + xreadlines method now work for unrolled files. encoding and newlines + - Issue #16686: Fixed a lot of bugs in audioop module. + - Issue #17073: Fix some integer overflows in sqlite3 module. + - Issue #6083: Fix multiple segmentation faults occured when + PyArg_ParseTuple parses nested mutating sequence. + - Issue #5289: Fix ctypes.util.find_library on Solaris. + - Issue #17106: Fix a segmentation fault in io.TextIOWrapper when an + underlying stream or a decoder produces data of an unexpected type (i.e. + when io.TextIOWrapper initialized with text stream or use bytes-to-bytes + codec). + - Issue #13994: Add compatibility alias in distutils.ccompiler for + distutils.sysconfig.customize_compiler. + - Issue #15633: httplib.HTTPResponse is now mark closed when the server + sends less than the advertised Content-Length. + - Issue #15881: Fixed atexit hook in multiprocessing. + - Issue #14340: Upgrade the embedded expat library to version 2.1.0. + - Issue #11159: SAX parser now supports unicode file names. + - Issue #6972: The zipfile module no longer overwrites files outside of + its destination path when extracting malicious zip files. + - Issue #17049: Localized calendar methods now return unicode if a locale + includes an encoding and the result string contains month or weekday (was + regression from Python 2.6). + - Issue #4844: ZipFile now raises BadZipfile when opens a ZIP file with an + incomplete "End of Central Directory" record. + - Issue #15505: `unittest.installHandler` no longer assumes SIGINT handler + is set to a callable object. + - Issue #17051: Fix a memory leak in os.path.isdir() on Windows. + - Issue #12268: The io module file object write methods no longer abort + early when a write system calls is interrupted (EINTR). + - Issue #17249: convert a test in test_capi to use unittest and reap + threads. + - We now run both test_email.py and test_email_renamed.py when running the + test_email regression test. test_email_renamed contains some tests that + test_email does not. + - Issue #17041: Fix testing when Python is configured with the + --without-doc-strings option. + - Issue #5033: Fix building of the sqlite3 extension module when the + SQLite library version has "beta" in it. + - Issue #17228: Fix building without pymalloc. + - Issue #17086: Backport the patches from the 3.3 branch to cross-build + the package. + - Issue #16406: combine the pages for uploading and registering to PyPI. + - Issue #16403: Document how distutils uses the maintainer field in + PKG-INFO. + - Issue #16695: Document how glob handles filenames starting with a dot. + - Issue #8890: Stop advertising an insecure practice by replacing uses + of the /tmp directory with better alternatives in the documentation. + - Issue #17203: add long option names to unittest discovery docs. + * python2.7-dbg, libpython2.7-dbg: Drop dependency on python. + * python2.7-dbg: Make gdb (not gdb-minimal) a recommendation. + * python2.7: Replace python2.7-minimal (<< 2.7.3-7). Closes: #702005. + * Build the _md5, _sha1, _sha256 and _sha512 extension modules. + * Fix multiarch include for AArch64. + + -- Matthias Klose Fri, 08 Mar 2013 09:54:59 +0800 + +python2.7 (2.7.3-15) experimental; urgency=low + + * Update to 20130124, taken from the 2.7 branch. + - Issue #14850: Now a charmap decoder treats U+FFFE as "undefined mapping" + in any mapping, not only in a Unicode string. + - Issue #11461: Fix the incremental UTF-16 decoder. + - Issue #1159051: GzipFile now raises EOFError when reading a corrupted + file with truncated header or footer. + - Issue #16992: On Windows in signal.set_wakeup_fd, validate the file + descriptor argument. + - Issue #15861: tkinter now correctly works with lists and tuples + containing strings with whitespaces, backslashes or unbalanced braces. + - Issue #10527: Use poll() instead of select() for multiprocessing pipes. + - Issue #9720: zipfile now writes correct local headers for files larger + than 4 GiB. + - Issue #16829: IDLE printing no longer fails if there are spaces or other + special characters in the file path. + - Issue #13899: \A, \Z, and \B now correctly match the A, Z, and B literals + when used inside character classes (e.g. '[\A]'). + - Issue #16398: Optimize deque.rotate() so that it only moves pointers + and doesn't touch the underlying data with increfs and decrefs. + - Issue #15109: Fix regression in sqlite3's iterdump method where it would + die with an encoding error if the database contained string values + containing non-ASCII. + - Issue #15545: Fix regression in sqlite3's iterdump method where it was + failing if the connection used a row factory (such as sqlite3.Row) that + produced unsortable objects. + - Issue #16953: Fix socket module compilation on platforms with + HAVE_BROKEN_POLL. + - Issue #16836: Enable IPv6 support even if IPv6 is disabled on the + build host. + - Issue #15539: Fix a number of bugs in Tools/scripts/pindent.py. + * Backport cross-build support from python3.3. LP: #873007. + * Add pyconfig.h compatibility headers. Closes: #695667. LP: #1094246. + + -- Matthias Klose Thu, 24 Jan 2013 14:57:08 +0100 + +python2.7 (2.7.3-14) experimental; urgency=low + + * Update to 20130105, taken from the 2.7 branch. + - Issue #16367: Fix FileIO.readall() on Windows for files larger than 2 GB. + - Issue #15516: Fix a bug in PyString_FromFormat where it failed + to properly ignore errors from a __int__() method. + - Issue #16839: Fix a segfault when calling unicode() on a classic class + early in interpreter initialization. + - Issue #16761: Calling ``int()`` and ``long()`` with *base* argument only + now raises TypeError. + - Issue #16828: Fix error incorrectly raised by bz2.compress(''). + LP: #1090043. + - Issue #16819: IDLE method completion now correctly works for unicode + literals. + - Issue 10527: make multiprocessing use poll() instead of select() + if available. + - Issue #16485: Now file descriptors are closed if file header patching + failed on closing an aifc file. + - Issue #12065: connect_ex() on an SSL socket now returns the original + errno when the socket's timeout expires (it used to return None). + - Issue #16504: IDLE now catches SyntaxErrors raised by tokenizer. + - Issue #16702: test_urllib2_localnet tests now correctly ignores proxies + for localhost tests. + - Issue #16713: Fix the parsing of tel url with params using urlparse + module. + - Issue #16443: Add docstrings to regular expression match objects. + - Issue #8853: Allow port to be of type long for socket.getaddrinfo(). + - Issue #16597: In buffered and text IO, call close() on the underlying + stream if invoking flush() fails. + - Issue #15701: Fix HTTPError info method call to return the headers + information. + - Issue #14958: Change IDLE systax highlighting to recognize all string + and byte literals currently supported in Python 2.7. + - Issue #15324: Fix regrtest parsing of --fromfile and --randomize options. + - Issue #16618: Add more regression tests for glob. + - Issue #13094: add "Why do lambdas defined in a loop with different values + all return the same result?" programming FAQ. + * python-config --help returns with an exit value 0. LP: #1093860. + * Update package description for the -dbg packages. Closes: #696616. + + -- Matthias Klose Sat, 05 Jan 2013 17:22:13 +0100 + +python2.7 (2.7.3-13) experimental; urgency=low + + * Update to 20121220, taken from the 2.7 branch. + - Issue #16646: ftplib.FTP.makeport() might lose socket error details. + - Issue #16298: In HTTPResponse.read(), close the socket when there is no + Content-Length and the incoming stream is finished. + * Filter out -D_FORTIFY_SOURCE for the debug builds. Meaningless. + * Install the _sysconfigdata.py and python-config.sh from both shared + builds, but don't link extensions against the shared python library. + Closes: #695979. + * Fix python2.7-dbg-config symlink. LP: #1091615. + * During purge, check for existance of /etc/python2.7 before trying + to remove it. Closes: #696023. + * python2.7-dev, libpython2.7-dev: Drop the dependency on libssl-dev. + * debian/patches/sys-multiarch.diff: Expose multiarch tuple as + sys._multiarch (Barry Warsaw). Closes: #695958. + Note: Usage of sysconfig.get_config_var('MULTIARCH') is preferred. + + -- Matthias Klose Thu, 20 Dec 2012 16:57:49 +0100 + +python2.7 (2.7.3-12) experimental; urgency=low + + * Fix typo in pkgconfig file. Closes: #695671, LP: #1088988. + + -- Matthias Klose Mon, 10 Dec 2012 19:10:32 +0100 + +python2.7 (2.7.3-11) experimental; urgency=low + + * Update to 20121210, taken from the 2.7 branch. + - Issue #16602: When a weakref's target was part of a long deallocation + chain, the object could remain reachable through its weakref even though + its refcount had dropped to zero. + - Issue #16588: Silence unused-but-set warnings in Python/thread_pthread. + - Issue #16248: Disable code execution from the user's home directory by + tkinter when the -E flag is passed to Python. Patch by Zachary Ware. + - Issue #16628: Fix a memory leak in ctypes.resize(). + - Issue #13614: Fix setup.py register failure with invalid rst in + description. + - Issue #10182: The re module doesn't truncate indices to 32 bits anymore. + - Issue #16573: In 2to3, treat enumerate() like a consuming call, so + superfluous list() calls aren't added to filter(), map(), and zip() + which are directly passed enumerate(). + - Issue #16476: Fix json.tool to avoid including trailing whitespace. + - Issue #16549: Add tests for json.tools. + - Issue #15990: Improve argument/parameter documentation. + * Use _sysconfigdata.py in distutils.sysconfig. + * Fix distutils.sysconfig.get_{config_h,makefile}_filename for multiarch. + * Backport ssl.match_hostname from Python3. Closes: #626539. + + -- Matthias Klose Mon, 10 Dec 2012 16:06:41 +0100 + +python2.7 (2.7.3-10) experimental; urgency=low + + * Update to 20121128, taken from the 2.7 branch. + - Issue #9011: Fix hacky AST code that modified the CST when compiling + a negated numeric literal. + - Issue #16306: Fix multiple error messages when unknown command line + parameters where passed to the interpreter. + - Issue #15379: Fix passing of non-BMP characters as integers for the + charmap decoder (already working as unicode strings). + - Issue #16453: Fix equality testing of dead weakref objects. + - Issue #9535: Fix pending signals that have been received but not yet + handled by Python to not persist after os.fork() in the child process. + - Issue #15001: fix segfault on "del sys.modules['__main__']". + - Issue #5057: the peepholer no longer optimizes subscription on unicode + literals (e.g. u'foo'[0]) in order to produce compatible pyc files + between narrow and wide builds. + - Issue #8401: assigning an int to a bytearray slice (e.g. b[3:4] = 5) + now raises an error. + - Issue #14700: Fix buggy overflow checks for large width and precision + in string formatting operations. + - Issue #16345: Fix an infinite loop when ``fromkeys`` on a dict subclass + received a nonempty dict from the constructor. + - Issue #6074: Ensure cached bytecode files can always be updated by the + user that created them, even when the source file is read-only. + - Issue #14783: Improve int() and long() docstrings and switch docstrings + for unicode(), slice(), range(), and xrange() to use multi-line + signatures. + - Issue #16030: Fix overflow bug in computing the `repr` of an xrange + object with large start, step or length. + - Issue #16029: Fix overflow bug occurring when pickling xranges with large + start, step or length. + - Issue #16037: Limit httplib's _read_status() function to work around + broken HTTP servers and reduce memory usage (backport of a 3.2 fix). + - Issue #13992: The trashcan mechanism is now thread-safe. This eliminates + sporadic crashes in multi-thread programs when several long deallocator + chains ran concurrently and involved subclasses of built-in container + types. + - Issue #15801: Make sure mappings passed to '%' formatting are actually + subscriptable. + - Issue #15604: Update uses of PyObject_IsTrue() to check for and handle + errors correctly. + - Issue #15897: zipimport.c doesn't check return value of fseek(). + - Issue #16369: Global PyTypeObjects not initialized with PyType_Ready(...). + - Issue #15033: Fix the exit status bug when modules invoked using + -m switch, return the proper failure return value (1). + - Issue #1160: Fix compiling large regular expressions on UCS2 builds. + - Issue #14313: zipfile now raises NotImplementedError when the compression + type is unknown. + - Issue #16408: Fix file descriptors not being closed in error conditions + in the zipfile module. + - Issue #16327: The subprocess module no longer leaks file descriptors + used for stdin/stdout/stderr pipes to the child when fork() fails. + - Issue #14396: Handle the odd rare case of waitpid returning 0 when not + expected in subprocess.Popen.wait(). + - Issue #16411: Fix a bug where zlib.decompressobj().flush() might try + to access previously-freed memory. + - Issue #16350: zlib.decompressobj().decompress() now accumulates data from + successive calls after EOF in unused_data, instead of only saving the + argument to the last call. decompressobj().flush() now correctly sets + unused_data and unconsumed_tail. A bug in the handling of MemoryError + when setting the unconsumed_tail attribute has also been fixed. + - Issue #12759: sre_parse now raises a proper error when the name + of the group is missing. + - Issue #16152: fix tokenize to ignore whitespace at the end of the code + when no newline is found. + - Issue #1207589: Add Cut/Copy/Paste items to IDLE right click + Context Menu. + - Issue #16230: Fix a crash in select.select() when one the lists changes + size while iterated on. + - Issue #16228: Fix a crash in the json module where a list changes size + while it is being encoded. + - Issue #14897: Enhance error messages of struct.pack and struct.pack_into. + - Issue #12890: cgitb no longer prints spurious

tags in text + mode when the logdir option is specified. + - Issue #14398: Fix size truncation and overflow bugs in the bz2 module. + - Issue #5148: Ignore 'U' in mode given to gzip.open() and gzip.GzipFile(). + - Issue #16220: wsgiref now always calls close() on an iterable response. + - Issue #16461: Wave library should be able to deal with 4GB wav files, + and sample rate of 44100 Hz. + - Issue #16176: Properly identify Windows 8 via platform.platform(). + - Issue #15756: subprocess.poll() now properly handles errno.ECHILD to + return a returncode of 0 when the child has already exited or cannot + be waited on. + - Issue #12376: Pass on parameters in TextTestResult.__init__ super call. + - Issue #15222: Insert blank line after each message in mbox mailboxes. + - Issue #16013: Fix CSV Reader parsing issue with ending quote characters. + - Issue #15421: fix an OverflowError in Calendar.itermonthdates() after + datetime.MAXYEAR. + - Issue #15970: xml.etree.ElementTree now serializes correctly the + empty HTML elements 'meta' and 'param'. + - Issue #15676: Now "mmap" check for empty files before doing the + offset check. + - Issue #15340: Fix importing the random module when /dev/urandom cannot + be opened. This was a regression caused by the hash randomization patch. + - Issue #15841: The readable(), writable() and seekable() methods of + io.BytesIO and io.StringIO objects now raise ValueError when the object + has been closed. + - Issue #16112: platform.architecture does not correctly escape argument to + /usr/bin/file. + - Issue #12776,#11839: call argparse type function (specified by + add_argument) only once. Before, the type function was called twice in + the case where the default was specified and the argument was given as + well. This was especially problematic for the FileType type, as a + default file would always be opened, even if a file argument was + specified on the command line. + - Issue #15906: Fix a regression in argparse caused by the preceding change, + when action='append', type='str' and default=[]. + - Issue #13370: Ensure that ctypes works on Mac OS X when Python is + compiled using the clang compiler + - Issue #15544: Fix Decimal.__float__ to work with payload-carrying NaNs. + - Issue #15199: Fix JavaScript's default MIME type to + application/javascript. + - Issue #15477: In cmath and math modules, add workaround for platforms + whose system-supplied log1p function doesn't respect signs of zeros. + - Issue #15908: Fix misbehaviour of the sha1 module when called on data + larger than 2**32 bytes. + - Issue #15910: Fix misbehaviour of _md5 and sha1 modules when "updating" + on data larger than 2**32 bytes. + - Fix the leak of a dict in the time module when used in an embedded + interpreter that is repeatedly initialized and shutdown and reinitialized. + - Issue #12268: File readline, readlines and read or readall methods + no longer lose data when an underlying read system call is interrupted + within an io module object. IOError is no longer raised due to a read + system call returning EINTR from within these methods. + - Issue #16012: Fix a regression in pyexpat. The parser's UseForeignDTD() + method doesn't require an argument again. + - Issue #16559: Add more tests for the json module, including some from the + official test suite at json.org. + - Issue #16274: Fix test_asyncore on Solaris. + - Issue #15040: Close files in mailbox tests for PyPy compatibility. + - Issue #15802: Fix test logic in TestMaildir.test_create_tmp. + - Issue #15765: Extend a previous fix to Solaris and OpenBSD for quirky + getcwd() behaviour (issue #9185) to NetBSD as well. + - Issue #15615: Add some tests for the json module's handling of invalid + input data. + - Issue #15923: fix a mistake in asdl_c.py that resulted in a TypeError + after 2801bf875a24 (see #15801). + - Issue #11715: Fix multiarch detection without having Debian development + tools (dpkg-dev) installed. + - Issue #15819: Make sure we can build Python out-of-tree from a readonly + source directory. (Somewhat related to Issue #9860.) + - Issue #15822: Ensure 2to3 grammar pickles are properly installed. + - Issue #13301: use ast.literal_eval() instead of eval() + in Tools/i18n/msgfmt.py. + - Issue #16400: Update the description of which versions of a given package + PyPI displays. + - Issue #15677: Document that zlib and gzip accept a compression level + of 0 to mean 'no compression'. + - Issue #8040: added a version switcher to the documentation. + - Issue #16115: Improve subprocess.Popen() documentation around args, + shell, and executable arguments. + - Issue #15979: Improve timeit documentation. + - Issue #16036: Improve documentation of built-in int()'s signature and + arguments. + - Issue #15935: Clarification of argparse docs, re: add_argument() type and + default arguments. + - Issue #13769: Document the effect of ensure_ascii to the return type + of JSON decoding functions. + - Issue #14880: Fix kwargs notation in csv.reader, + .writer & .register_dialect. + - Issue #14674: Add a discussion of the json module's standard compliance. + * Clarify location of the gdbinit file. LP: #975676. + * Fix traceback for missing distutils wininst .exe files. LP: #1081155. + * Backport python3.3 multiarch packaging changes (Riku Voipio), and fix + multiarch issues discovered after the backport. + Closes: #683755. + * Use a shell implementation for the python-config script. + + -- Matthias Klose Thu, 29 Nov 2012 20:18:20 +0100 + +python2.7 (2.7.3-5) unstable; urgency=low + + * Enable verbose build for the sharedmods target. + * Fix issue #15847: allow args to be a tuple in parse_args. Closes: #686583. + * Fix issue #15340: Fix importing the random module when /dev/urandom cannot + be opened. Regression caused by the hash randomization patch. + * Don't use `-n' anymore to start idle in the desktop/menu files, not + needed anymore for multiseat installations. + + -- Matthias Klose Sun, 09 Sep 2012 16:54:26 +0200 + +python2.7 (2.7.3-4) unstable; urgency=low + + * Follwup for issue #9374. Restore the removed attributes in the + urlparse module. + * Update symbols files. + * Disable test_subprocess on the Hurd buildds. + * Call dh_movefiles with --srcdir. Closes: #685543. + + -- Matthias Klose Sun, 26 Aug 2012 12:24:31 +0200 + +python2.7 (2.7.3-3) unstable; urgency=low + + * Update to 20120814, taken from the 2.7 branch. Posix relevant patches: + - Issue #15041: Update "see also" list in tkinter documentation. + - Issue #14579: Fix error handling bug in the utf-16 decoder. + - Issue #15368: An issue that caused bytecode generation to be + non-deterministic when using randomized hashing (-R) has been fixed. + - Issue #15567: Fix NameError when running threading._test + - Issue #15424: Add a __sizeof__ implementation for array objects. + - Issue #13052: Fix IDLE crashing when replace string in Search/Replace + dialog ended with '\'. + - Issue #15538: Fix compilation of the getnameinfo() / getaddrinfo() + emulation code. + - Issue #9803: Don't close IDLE on saving if breakpoint is open. + - Issue #12288: Consider '0' and '0.0' as valid initialvalue + for tkinter SimpleDialog. + - Issue #15489: Add a __sizeof__ implementation for BytesIO objects. + - Issue #15469: Add a __sizeof__ implementation for deque objects. + - Issue #15487: Add a __sizeof__ implementation for buffered I/O objects. + - Issue #15512: Add a __sizeof__ implementation for parser. + - Issue #15402: An issue in the struct module that caused sys.getsizeof to + return incorrect results for struct.Struct instances has been fixed. + - Issue #15232: when mangle_from is True, email.Generator now correctly + mangles lines that start with 'From ' that occur in a MIME preamble + or epilog. + - Issue #13922: argparse no longer incorrectly strips '--'s that appear + after the first one. + - Issue #12353: argparse now correctly handles null argument values. + - Issue #14635: telnetlib will use poll() rather than select() when possible + to avoid failing due to the select() file descriptor limit. + - Issue #6056: Make multiprocessing use setblocking(True) on the + sockets it uses. + - Issue #15630: Add an example for "continue" stmt in the tutorial. + - Issue #15250: Document that filecmp.dircmp compares files shallowly. + * Fortified build. + * Python/import.c: Don't export isdir(). + * Modules/socketmodule.c: Don't export netdb_lock. + * Add breaks for vim-{nox,gtk,gnome,athena}. Closes: #682034. + * Don't ship python2.pc, should be shipped with python-dev instead. + Closes: #684612. + + -- Matthias Klose Tue, 14 Aug 2012 17:55:32 +0200 + +python2.7 (2.7.3-2) unstable; urgency=low + + * Update to 20120713, taken from the 2.7 branch. + - Issue #15033: Fix the exit status bug when modules invoked using -m swith, + return the proper failure return value (1). + - Issue #12268: File readline, readlines and read() methods no longer lose + data when an underlying read system call is interrupted. IOError is no + longer raised due to a read system call returning EINTR from within these + methods. + - Issue #13512: Create ~/.pypirc securely (CVE-2011-4944). + - Issue #7719: Make distutils ignore ``.nfs*`` files instead of choking + later on. + - Issue #10053: Don't close FDs when FileIO.__init__ fails. + - Issue #15247: FileIO now raises an error when given a file descriptor + pointing to a directory. + - Issue #14591: Fix bug in Random.jumpahead that could produce an invalid + Mersenne Twister state on 64-bit machines. + - Issue #5346: Preserve permissions of mbox, MMDF and Babyl mailbox + files on flush(). + - Issue #15219: Fix a reference leak when hashlib.new() is called with + invalid parameters. + - Issue #9559: If messages were only added, a new file is no longer + created and renamed over the old file when flush() is called on an + mbox, MMDF or Babyl mailbox. + - Issue #14653: email.utils.mktime_tz() no longer relies on system + mktime() when timezone offest is supplied. + - Issue #15101: Make pool finalizer avoid joining current thread. + - Issue #15054: A bug in tokenize.tokenize that caused string literals + with 'b' and 'br' prefixes to be incorrectly tokenized has been fixed. + - Issue #15036: Mailbox no longer throws an error if a flush is done + between operations when removing or changing multiple items in mbox, + MMDF, or Babyl mailboxes. + - Issue #15043: test_gdb is now skipped entirely if gdb security settings + block loading of the gdb hooks + - Issue #13557: Clarify effect of giving two different namespaces to exec or + execfile(). + * Don't build the _hashlib and _ssl extensions as a builtin, but as + extensions. Closes: #680930. + * Backport issue #13150: sysconfig no longer parses the Makefile and config.h + files when imported, instead doing it at build time. This makes importing + sysconfig faster and reduces Python startup time by 20%. + * python2.7: Add a break for python-virtualenv (<< 1.7.1.2-2~). + * Don't run the test_gdb test on mips/mipsel, not even in debug mode. + * For lto builds, use -g instead of -g1; filter out lto flags in the + installed Makefile. Closes: #681348. + + -- Matthias Klose Fri, 13 Jul 2012 05:03:43 +0200 + +python2.7 (2.7.3-1) unstable; urgency=low + + * Python 2.7.3 release. + * Update to 20120615, taken from the 2.7 branch. + * The wininst-* files cannot be built within Debian from the included + sources, needing a zlib mingw build, which the zlib maintainer isn't + going to provide. Closes: #639407. + * Let pydoc handle dist-packages the same as site-packages. + Closes: #671021. + * python2.7-doc: Fix underscore.js symlink. Closes: #671795, #676339. + * Do not italicize punctuation in python(1) manual page (Matt Kraai). + Closes: #579269. + * Build _heapq as a builtin (and move it to -minimal). + + -- Matthias Klose Fri, 15 Jun 2012 15:26:21 +0200 + +python2.7 (2.7.3~rc2-2.1) unstable; urgency=low + + * Non-maintainer upload (with maintainer's permission). + * Disable testsuite on GNU/kFreeBSD. (Closes: #669281) + + -- Robert Millan Sun, 22 Apr 2012 22:04:26 +0200 + +python2.7 (2.7.3~rc2-2) unstable; urgency=low + + * Use xdg-open/gvfs-open in Lib/webbrowser.py (Michael Vogt). + LP: #971311. + * Add a paragraph about python-foo-dbg packages to README.debug. + LP: #872050. + * Disable some tests (no feedback from porters): + - test_socket on hurd-i386. + - test_io on amd64. + - test_signal on kfreebsd-*. Closes: #654783. + - test_threading on sparc. + * Tighten build dependency on libexpat-dev. Closes: #665346. + * Build-depend on db-5.1, don't care about testsuite regressions on + some esoteric ports. If packages rely on threaded applications or + transactions, please use the python-bsddb3 package. + Closes: #621374. + * Don't ship the python2 and python2-config symlinks, move these + to the python-minimal and python-dev packages. Closes: #663874. + * Remove PVER-doc.doc-base.PVER-doc.in. Closes: #656763. + * Update symbols files. + * Avoid runtime path for the sqlite extension. + * CVE-2011-4944, distutils creates ~/.pypirc insecurely. Closes: #650555. + * Fix issue #14505, file descriptor leak when deallocating file objects + created with PyFile_FromString(). Closes: #664529. + + -- Matthias Klose Thu, 05 Apr 2012 15:47:03 +0200 + +python2.7 (2.7.3~rc2-1) unstable; urgency=low + + * Python 2.7.3 release candidate 2. + * Build-depend on expat >= 2.1~. + + -- Matthias Klose Wed, 21 Mar 2012 05:21:47 +0100 + +python2.7 (2.7.3~rc1-1) unstable; urgency=low + + * Python 2.7.3 release candidate 1. + * Update to 20120309, taken from the 2.7 branch. + * Fix dangling libpython.a symlink. Closes: #660231. + + -- Matthias Klose Fri, 09 Mar 2012 19:28:43 +0100 + +python2.7 (2.7.2-13) unstable; urgency=low + + * Update to 20120120, taken from the 2.7 branch. + * Remove patch integrated upstream (issue9054.diff). + * Backport Issue #9189 to distutils/sysconfig.py as well. + Closes: #656118. + * Disable test_io on kfreebsd again. Closes: #654783. + * Disable test_bsddb3 tests on kfreebsd again. + + -- Matthias Klose Fri, 20 Jan 2012 16:33:47 +0100 + +python2.7 (2.7.2-12) unstable; urgency=low + + * Run the tests with a script command which doesn't exit immediatly + when stdin is /dev/null (Colin Watson). + + -- Matthias Klose Fri, 13 Jan 2012 11:04:31 +0100 + +python2.7 (2.7.2-11) unstable; urgency=low + + * Don't run the test_site tests when $HOME doesn't exist. + + -- Matthias Klose Wed, 11 Jan 2012 09:19:00 +0100 + +python2.7 (2.7.2-10) unstable; urgency=low + + * Update to 20120110, taken from the 2.7 branch. + * Overwrite some lintian warnings: + - The -dbg interpreters are not unusual. + - The -gdb.py files don't need a python dependency. + - lintian can't handle a whatis entry starting with one word on the line. + * Fix test failures related to distutils debian installation layout. + * Add build-arch/build-indep targets. + * Regenerate Setup and Makefiles after correcting Setup.local. + * profiled-build.diff: Pass PY_CFLAGS instead of CFLAGS for the profiled + build. + * Pass dpkg-buildflags to the build process, and build third party + extensions with these flags. + * Add support to build using -flto (and -g1) on some architectures. + * Disable pgo builds for some architectures (for now, keep just + amd64 armel armhf i386 powerpc ppc64). + * Build-depend on libgdbm-dev to build and run the gdbm tests. + * Build-depend on xvfb to run the tkinter tests. + * python2.7: Provide python2.7-argparse and python-argparse. + * Don't run test_threading on mips/mipsel. + * Run the test_gdb test for the debug build only. + * Add build conflict to python-cxx-dev (pydoc test failures). + * Disable test_ssl certificate check, certificate expired on python.org. + + -- Matthias Klose Tue, 10 Jan 2012 16:44:56 +0100 + +python2.7 (2.7.2-9) unstable; urgency=low + + * Update to 20111217, taken from the 2.7 branch. + + -- Matthias Klose Sat, 17 Dec 2011 17:36:27 +0100 + +python2.7 (2.7.2-8) unstable; urgency=low + + * Update to 20111130, taken from the 2.7 branch. + * New patch, ctypes-arm, allow for ",hard-float" after libc6 in ldconfig -p + output (Loic Minier). LP: #898172. + * debian/rules: Define DPKG_VARS (Alban Browaeys). Closes: #647419). + * Add python-config man page (Johann Felix Soden). Closes: #650181). + + -- Matthias Klose Wed, 30 Nov 2011 19:16:23 +0100 + +python2.7 (2.7.2-7) unstable; urgency=low + + * Adjust patches for removed Lib/plat-linux3. + * Add build conflict to libncurses5-dev, let configure search for + ncurses headers in /usr/include/ncursesw too. + + -- Matthias Klose Wed, 05 Oct 2011 11:30:16 +0200 + +python2.7 (2.7.2-6) unstable; urgency=low + + * Update to 20111004, taken from the 2.7 branch. + * Use the ncursesw include directory when linking with ncursesw. + * Rebuild with libreadline not linked with libncurses*. Closes: #643816. + * Fix typos in the multiprocessing module. Closes: #643856. + + -- Matthias Klose Tue, 04 Oct 2011 16:09:29 +0200 + +python2.7 (2.7.2-5) unstable; urgency=low + + * Update to 20110816, taken from the 2.7 branch. + - Fix issue#12752. LP: #824734. + * Don't run test_threading on the kfreebsd-i386 buildd. + + -- Matthias Klose Tue, 16 Aug 2011 08:33:31 +0200 + +python2.7 (2.7.2-4) unstable; urgency=low + + * Update to 20110803, taken from the 2.7 branch. + * Fix build on s390x. Closes: #636033. + * Use linux-any for some build dependencies. Closes: #634809. + * Revert previous change to treat Linux 3.x as Linux 2. Use the + plat-linux3 directory instead. + + -- Matthias Klose Wed, 03 Aug 2011 12:36:05 +0200 + +python2.7 (2.7.2-3) unstable; urgency=low + + * Update to 20110709, taken from the 2.7 branch. + * Make the conflict against python-profiler a versioned conflict. + * Don't run the bsddb3 tests on kfreebsd-i386. + * Don't add the bsddb multilib path, if already in the standard lib path. + * Treat Linux 3.x as Linux 2. Closes: #633015. + * Assume working semaphores on Linux, don't rely on running kernel + for the check. Closes: #631188. + + -- Matthias Klose Sat, 09 Jul 2011 13:19:47 +0200 + +python2.7 (2.7.2-2) unstable; urgency=low + + * Update to 20110628, taken from the 2.7 branch. + * Add profile/pstats to the python2.7 package, update debian copyright. + * Don't run the bsddb3 tests on kfreebsd-amd64. + * Don't run the benchmark on hurd-i386. + + -- Matthias Klose Tue, 28 Jun 2011 23:05:21 +0200 + +python2.7 (2.7.2-1) unstable; urgency=low + + * Python 2.7.2 release. + + -- Matthias Klose Sun, 12 Jun 2011 21:04:24 +0200 + +python2.7 (2.7.2~rc1-2) unstable; urgency=medium + + * Set pyexpat dummy version string. + + -- Matthias Klose Tue, 31 May 2011 12:05:56 +0200 + +python2.7 (2.7.2~rc1-1) unstable; urgency=low + + * Python 2.7.2 release candidate 1. + * Update libpython symbols file for m68k (Thorsten Glaser). Closes: #627458. + * Apply proposed patch for issue #670664. LP: #357067. + + -- Matthias Klose Mon, 30 May 2011 06:44:23 +0200 + +python2.7 (2.7.1-9) unstable; urgency=low + + * Update to 20110520, taken from the 2.7 branch. + + -- Matthias Klose Fri, 20 May 2011 13:43:12 +0200 + +python2.7 (2.7.1-8) unstable; urgency=low + + * Keep the ssl.PROTOCOL_SSLv2 module constant , just raise an exception + when trying to create a PySSL object. Closes: #623423. + + -- Matthias Klose Wed, 20 Apr 2011 12:31:03 +0200 + +python2.7 (2.7.1-7) unstable; urgency=low + + * Update to 20110419, taken from the 2.7 branch. + * Build without OpenSSL v2 support. Closes: #620581. + * Force linking the curses module against libncursesw. Closes: #622064. + * Link libpython with --whole-archive. Closes: #614711. + * Re-enable running the testsuite during the build. + + -- Matthias Klose Tue, 19 Apr 2011 17:36:56 +0200 + +python2.7 (2.7.1-6) unstable; urgency=low + + * Update to 20110307, taken from the 2.7 branch. + * Disable the profile guided build on ia64, sparc. + + -- Matthias Klose Mon, 07 Mar 2011 02:19:02 +0100 + +python2.7 (2.7.1-5) experimental; urgency=low + + * Update to 20110224, taken from the 2.7 branch. + * Update patches. + * Re-enable profile guided build. + + -- Matthias Klose Thu, 24 Feb 2011 06:01:42 +0100 + +python2.7 (2.7.1-4) experimental; urgency=low + + * Update to 20110119, taken from the 2.7 branch. + + -- Matthias Klose Wed, 19 Jan 2011 04:21:14 +0100 + +python2.7 (2.7.1-3) experimental; urgency=low + + * Do not run test_multiprocessing when running the testsuite. + Fails on armel and powerpc on some buildds. + + -- Matthias Klose Fri, 24 Dec 2010 01:46:55 +0100 + +python2.7 (2.7.1-2) experimental; urgency=low + + * Update to 20101222, taken from the 2.7 branch. + * Re-enable the distutils-sysconfig.diff patch, apparently + lost when updating the patches for 2.7. + * Disable the profiled builds on all architectures. + + -- Matthias Klose Wed, 22 Dec 2010 15:39:48 +0100 + +python2.7 (2.7.1-1) experimental; urgency=low + + * Python 2.7.1 release. + + -- Matthias Klose Sun, 28 Nov 2010 12:05:23 +0100 + +python2.7 (2.7.1~rc1-2) experimental; urgency=low + + * Move the pyconfig.h file into the -min package, required by sysconfig. + Closes: #603237. + + -- Matthias Klose Sun, 14 Nov 2010 09:40:09 +0100 + +python2.7 (2.7.1~rc1-1) experimental; urgency=low + + * Python 2.7.1 release candidate 1. + * Move the Makefile into the -min package, required by sysconfig. + Closes: #603237. + + -- Matthias Klose Sun, 14 Nov 2010 00:33:48 +0100 + +python2.7 (2.7-9) experimental; urgency=low + + * Update to 20101016, taken from the 2.7 branch. + + -- Matthias Klose Sat, 16 Oct 2010 12:46:57 +0200 + +python2.7 (2.7-8) experimental; urgency=low + + * Disabled the profiled build on armel. + + -- Matthias Klose Thu, 23 Sep 2010 15:06:06 +0200 + +python2.7 (2.7-7) experimental; urgency=low + + * Update to 20100922, taken from the 2.7 branch. + * Update GNU/Hurd patches (Pino Toscano). Closes: #597419. + + -- Matthias Klose Wed, 22 Sep 2010 20:35:24 +0200 + +python2.7 (2.7-6) experimental; urgency=low + + * Update to 20100915, taken from the 2.7 branch. + - Fix issue #9729, Unconnected SSLSocket.{send,recv} raises TypeError + (Andrew Bennetts). LP: #637821. + * Add copyright information for expat, libffi and zlib. Addresses: #596276. + * Apply proposed fix for issue 9054, configure --with-system-expat. + * Provide Lib/plat-gnukfreebsd[78] (Jakub Wilk). Addresses: #593818. + + -- Matthias Klose Wed, 15 Sep 2010 17:43:18 +0200 + +python2.7 (2.7-5) experimental; urgency=low + + * Update to 20100829, taken from the 2.7 branch. + * Don't configure --with-system-expat, segfaults the interpreter in the + testsuite. + * Disable more tests on hppa and hurd-i386, which fail on the buildds. + + -- Matthias Klose Sun, 29 Aug 2010 16:22:37 +0200 + +python2.7 (2.7-4) experimental; urgency=low + + * Update to 20100822, taken from the 2.7 branch. + * Fixed in previous 2.7 uploads: Multiple integer overflows in audioop.c + in the audioop module (CVE-2010-1634). + * Fix some lintian warnings. + * Configure --with-system-expat. + + -- Matthias Klose Mon, 23 Aug 2010 13:03:40 +0200 + +python2.7 (2.7-3) experimental; urgency=low + + * Update to 20100807, taken from the 2.7 branch. + * Move '/usr/local/.../dist-packages' before '/usr/lib/.../dist-packages' + in sys.path. Adresses: #588342. + * Fix detection of ffi.h header file. Closes: #591408. + * python2-7-dev: Depend on libssl-dev. LP: #611845. + + -- Matthias Klose Sat, 07 Aug 2010 21:28:04 +0200 + +python2.7 (2.7-2) experimental; urgency=low + + * Complete debug-build.diff, some parts lost in quilt conversion. + * Move the pkgconfig file into the -dev package. + + -- Matthias Klose Tue, 06 Jul 2010 21:07:48 +0200 + +python2.7 (2.7-1) experimental; urgency=low + + * Python 2.7 release. + * Update to 20100706, taken from the trunk. + * Update symbols files. + + -- Matthias Klose Tue, 06 Jul 2010 07:21:23 +0200 + +python2.7 (2.7~rc2-3) experimental; urgency=low + + * Update to 20100703, taken from the trunk. + * Move the _weakrefset module, not extension to -minimal. Closes: #587568. + * Move the sysconfig module to -minimal. Closes: #586113. + * Move the shutil module to python2.6-minimal. Addresses: #587628. + + -- Matthias Klose Sat, 03 Jul 2010 13:27:36 +0200 + +python2.7 (2.7~rc2-2) experimental; urgency=low + + * Fix applying plat-linux2* patches. + * Use the profiled build on armel, sparc and sparc64. + + -- Matthias Klose Tue, 29 Jun 2010 08:04:59 +0200 + +python2.7 (2.7~rc2-1) experimental; urgency=low + + * Python 2.7 release candidate 2. + * Update to 20100628, taken from the trunk. + * Merge packaging changes from python2.6 (2.6.5+20100628-1). + + -- Matthias Klose Tue, 29 Jun 2010 00:57:00 +0200 + +python2.7 (2.7~b1-2) experimental; urgency=low + + * Update to 20100508, taken from the trunk. + + -- Matthias Klose Sat, 08 May 2010 17:34:07 +0200 + +python2.7 (2.7~b1-1) experimental; urgency=low + + * Python 2.7 beta1. + * Update to 20100420, taken from the trunk. + * Update libpython symbols files. + * Apply proposed patch for issue #7332, segfaults in + PyMarshal_ReadLastObjectFromFile in import_submodule. + * Don't build-depend on locales on avr32. Closes: #575144. + + -- Matthias Klose Tue, 20 Apr 2010 23:53:42 +0200 + +python2.7 (2.7~a4-1) experimental; urgency=low + + * Python 2.7 alpha4. + * Update to 20100316, taken from the trunk. + * Point distutils.sysconfig to the system installation. Closes: #573363. + + -- Matthias Klose Tue, 16 Mar 2010 15:45:07 +0100 + +python2.7 (2.7~a3-1) experimental; urgency=low + + * Python 2.7 alpha3. + + -- Matthias Klose Tue, 16 Feb 2010 03:04:01 +0100 + +python2.7 (2.7~a2-1) experimental; urgency=low + + * Python 2.7 alpha2. + + -- Matthias Klose Sat, 16 Jan 2010 14:49:59 +0100 + +python2.6 (2.6.5+20100628-1) unstable; urgency=low + + * Update to 20100614, taken from the 2.6 release branch (r82337). + * Apply plat-linux2- patch for alpha, hppa, mips, mipsel, sparc + and sparc64. + + -- Matthias Klose Mon, 28 Jun 2010 21:26:43 +0200 + +python2.6 (2.6.5+20100626-1) unstable; urgency=low + + * Update to 20100614, taken from the 2.6 release branch (r82245). + * Update libpython symbols files. Closes: #587012. + * Move the logging package and the runpy module to python2.6-minimal. + + -- Matthias Klose Sat, 26 Jun 2010 14:29:41 +0200 + +python2.6 (2.6.5+20100616-1) unstable; urgency=medium + + * Update to 20100614, taken from the 2.6 release branch (r81601). + * Reapply the backport for issue #8233, lost in the conversion to + quilt. + * Disable the profiled build on alpha. + * Make pydoc more robust not to fail on exceptions other than import + exceptions. + * posixmodule: Add flags for statvfs.f_flag to constant list. + + -- Matthias Klose Wed, 16 Jun 2010 07:56:40 +0200 + +python2.6 (2.6.5+20100529-1) unstable; urgency=low + + * Update to 20100529, taken from the 2.6 release branch (r81601). + - Fix issue #5753, CVE-2008-5983 python: untrusted python modules + search path. Closes: #572010. + * Convert internal dpatch system to quilt. + * Build the ossaudio extension on GNU/kFreeBSD. Closes: #574696. + + -- Matthias Klose Sat, 29 May 2010 15:07:51 +0200 + +python2.6 (2.6.5-2) unstable; urgency=low + + * Update libpython symbols files. + * debian/patches/issue8032.dpatch: Update to version from the + trunk. + * Fix issue #8329: Don't return the same lists from select.select + when no fds are changed. + * Fix issue #8310: Allow dis to examine new style classes. + * Fix issues #8279: Fix test_gdb failures. + * Fix issue #8233: When run as a script, py_compile.py optionally + takes a single argument `-`. + * Apply proposed patch for issue #7332, segfaults in + PyMarshal_ReadLastObjectFromFile in import_submodule. + * Don't build-depend on locales on avr32. Closes: #575144. + + -- Matthias Klose Tue, 20 Apr 2010 19:41:36 +0200 + +python2.6 (2.6.5-1ubuntu6) lucid; urgency=low + + * Fix applying patch for issue #8310. + + -- Matthias Klose Fri, 16 Apr 2010 14:20:35 +0200 + +python2.6 (2.6.5-1ubuntu5) lucid; urgency=low + + * Fix issue #8329: Don't return the same lists from select.select + when no fds are changed. + * Fix issue #8310: Allow dis to examine new style classes. + + -- Matthias Klose Thu, 15 Apr 2010 01:21:07 +0200 + +python2.6 (2.6.5-1ubuntu4) lucid; urgency=low + + * debian/patches/issue8032.dpatch: Update to version from the + trunk. Upload for beta2 to avoid apport errors. + - Handle PyFrameObject's: LP: #543624, #548723. + - Detect cycles in object reference graph and add extra + protection: LP: #544823, LP: #552356. + + -- Matthias Klose Thu, 01 Apr 2010 22:53:06 +0200 + +python2.6 (2.6.5-1ubuntu3) lucid; urgency=low + + * debian/patches/issue8140.dpatch: Incomplete patch; regenerate. + * debian/patches/issue8032.dpatch: Update to v4: + - Add support for PySetObject (set/frozenset). + - Add support for PyBaseExceptionObject (BaseException). + - Fix a signed vs unsigned char issue that led to exceptions + in gdb for PyStringObject instances. + - Handle the case of loops in the object reference graph. + - Unit tests for all of the above. + + -- Matthias Klose Wed, 31 Mar 2010 18:52:32 +0200 + +python2.6 (2.6.5-1ubuntu2) lucid; urgency=low + + * Disable profiled build on powerpc. + + -- Matthias Klose Sat, 20 Mar 2010 15:17:18 +0100 + +python2.6 (2.6.5-1ubuntu1) lucid; urgency=low + + * Merge with Debian (2.6.5-1). + + -- Matthias Klose Sat, 20 Mar 2010 03:57:17 +0100 + +python2.6 (2.6.5-1) unstable; urgency=low + + * Python 2.6.5 final release. + * Fix issue #4961: Inconsistent/wrong result of askyesno function in + tkMessageBox with Tcl8.5. LP: #462950. + * Issue #8154, fix segfault with os.execlp('true'). LP: #418848. + * Apply proposed patch for issue #8032, gdb7 hooks for debugging. + + -- Matthias Klose Fri, 19 Mar 2010 00:12:55 +0100 + +python2.6 (2.6.5~rc2-2) unstable; urgency=low + + * Add copyright notices for the readline and _ssl extensions. + Closes: #573866. + * Backport issue #8140: Extend compileall to compile single files. + Add -i option. + * Backport issue #6949, build _bsddb extension with db-4.8.x. + + -- Matthias Klose Tue, 16 Mar 2010 03:02:21 +0100 + +python2.6 (2.6.5~rc2-1) unstable; urgency=low + + * Python 2.6.5 release candidate 2. + - Replace the Monty Python audio test file. Closes: #568674. + * Fix build failure on sparc64. Closes: #570845. + + -- Matthias Klose Thu, 11 Mar 2010 16:50:03 +0100 + +python2.6 (2.6.5~rc2-0ubuntu1) lucid; urgency=low + + * Python 2.6.5 release candidate 2. + + -- Matthias Klose Thu, 11 Mar 2010 13:30:19 +0100 + +python2.6 (2.6.4-6ubuntu1) lucid; urgency=low + + * Merge with Debian (2.6.4-6). + + -- Matthias Klose Tue, 16 Feb 2010 01:08:50 +0100 + +python2.6 (2.6.4-6) unstable; urgency=low + + * Update to 20100215, taken from the 2.6 release branch. + * python2.6-minimal: Skip moving syssite contents to new location, if + /usr/local/lib/python2.6 cannot be written. Closes: #569532. LP: #338227. + * libpython2.6: Fix symlink in /usr/lib/python2.6/config. LP: #521050. + + -- Matthias Klose Mon, 15 Feb 2010 22:12:18 +0100 + +python2.6 (2.6.4-5ubuntu1) lucid; urgency=low + + * Merge with Debian (2.6.4-5). + + -- Matthias Klose Sun, 31 Jan 2010 22:31:41 +0100 + +python2.6 (2.6.4-5) unstable; urgency=low + + * Update to 20100131, taken from the 2.6 release branch. + - Fix typo in os.execvp docstring. Closes: #558764. + * distutils.sysconfig.get_python_lib(): Only return ".../dist-packages" if + prefix is the default prefix and if PYTHONUSERBASE is not set in the + environment and if --user option is not present. LP: #476005. + * distutils install: Don't install into /usr/local/local, if option + --prefix=/usr/local is present, without changing the install prefix. + LP: #510211. + + -- Matthias Klose Sun, 31 Jan 2010 21:16:51 +0100 + +python2.6 (2.6.4-4ubuntu1) lucid; urgency=low + + * Update to 20100122, taken from the 2.6 release branch. + - Fix DoS via XML document with malformed UTF-8 sequences (CVE_2009_3560). + Closes: #566233. + - Fix typo in os.execvp docstring. Closes: #558764. + * python2.6-doc: Fix searching in local documentation. LP: #456025. + * Update locale module from the trunk. LP: #223281. + * Merge with Debian (2.6.4-4). + + -- Matthias Klose Fri, 22 Jan 2010 11:37:29 +0100 + +python2.6 (2.6.4-4) unstable; urgency=low + + * Update to 20100122, taken from the 2.6 release branch. + - Fix DoS via XML document with malformed UTF-8 sequences (CVE_2009_3560). + Closes: #566233. + * Hurd fixes (Pino Toscano). Closes: #565693: + - hurd-broken-poll.dpatch: ported from 2.5. + - hurd-disable-nonworking-constants.dpatch: disable a few constants from + the public API whose C counterparts are not implemented, so using them + either always blocks or always fails (caused issues in the test suite). + - Exclude the profiled build for hurd. + - Disable four blocking tests from the test suite. + + -- Matthias Klose Fri, 22 Jan 2010 11:10:41 +0100 + +python2.6 (2.6.4-3) unstable; urgency=low + + * Disable the profiled build on s390, mips, mipsel. + * Fix symbol files for kfreebsd-amd64 and sparc64. + + -- Matthias Klose Sat, 16 Jan 2010 16:12:17 +0100 + +python2.6 (2.6.4-2) unstable; urgency=low + + * Update to 20100116, taken from the 2.6 release branch. + * Fix bashism in makesetup shell script. Closes: #530170, #530171. + * Fix build issues on avr (Bradley Smith). Closes: #528439. + - Configure --without-ffi. + - Don't run lengthly tests. + * locale.py: Update locale aliases from the 2.7 branch. + + -- Matthias Klose Sat, 16 Jan 2010 11:05:12 +0100 + +python2.6 (2.6.4-1) experimental; urgency=low + + * Python 2.6.4 final release. + - Issue #7120: logging: Removed import of multiprocessing which is causing + crash in GAE. + - Issue #7149: fix exception in urllib when detecting proxy settings + on OSX. + - Issue #7115: Fixed the extension module builds that is failing when + using paths in the extension name instead of dotted names. LP: #449734. + - Issue #6894: Fixed the issue urllib2 doesn't respect "no_proxy" + environment. + - Issue #7052: Removed nonexisting NullHandler from logging.__all__. + - Issue #7039: Fixed distutils.tests.test_sysconfig when running on + installation with no build. + - Issue #7019: Raise ValueError when unmarshalling bad long data, instead + of producing internally inconsistent Python longs. + * distutils install: Don't install into /usr/local/local, if option + --prefix=/usr/local is present. + + -- Matthias Klose Tue, 27 Oct 2009 01:22:21 +0100 + +python2.6 (2.6.4~rc1-1) experimental; urgency=low + + * Python 2.6.4 release candidate 1. + - Issue #7052: Removed nonexisting NullHandler from logging.__all__. + - Issue #7039: Fixed distutils.tests.test_sysconfig when running on + installation with no build. + - Issue #7019: Raise ValueError when unmarshalling bad long data, instead + of producing internally inconsistent Python longs. + - Issue #7068: Fixed the partial renaming that occured in r72594. + - Issue #7042: Fix test_signal (test_itimer_virtual) failure on OS X 10.6. + * Remove the conflict with python-setuptools (fixed in issue #7068). + * Build _hashlib as a builtin. + * python2.6-doc: Don't compress the sphinx inventory. + * python2.6-doc: Fix jquery.js symlink. + + -- Matthias Klose Sat, 10 Oct 2009 10:21:02 +0200 + +python2.6 (2.6.3-1) experimental; urgency=low + + * Final Python 2.6.3 release. + - Issue #5329: Fix os.popen* regression from 2.5 with commands as a + sequence running through the shell. + - Issue #6990: Fix threading.local subclasses leaving old state around + after a reference cycle GC which could be recycled by new locals. + - Issue #6790: Make it possible again to pass an `array.array` to + `httplib.HTTPConnection.send`. + - Issue #6922: Fix an infinite loop when trying to decode an invalid + UTF-32 stream with a non-raising error handler like "replace" or + "ignore". + - Issue #1590864: Fix potential deadlock when mixing threads and fork(). + - Issue #6844: Do not emit DeprecationWarnings when accessing a "message" + attribute on exceptions that was set explicitly. + - Issue #6236, #6348: Fix various failures in the `io` module under AIX + and other platforms, when using a non-gcc compiler. Patch by egreen. + - Issue #6851: Fix urllib.urlopen crash on secondairy threads on OSX 10.6 + - Issue #6947: Fix distutils test on windows. Patch by Hirokazu Yamamoto. + - Issue #4606: Passing 'None' if ctypes argtype is set to POINTER(...) + does now always result in NULL. + - Issue #5042: ctypes Structure sub-subclass does now initialize + correctly with base class positional arguments. + - Issue #6938: Fix a TypeError in string formatting of a multiprocessing + debug message. + - Issue #6944: Fix a SystemError when socket.getnameinfo() was called + with something other than a tuple as first argument. + - Issue #6980: Fix ctypes build failure on armel-linux-gnueabi with + -mfloat-abi=softfp. + * python2.6-dbg: Don't create debug subdirectory in /usr/local. No + separate debug directory needed anymore. + * Run the benchmark with -C 2 -n 5 -w 4 on all architectures. + * Build-depend on the versioned db4.x-dev to avoid unexpected updates + for anydbm databases. + + -- Matthias Klose Sat, 03 Oct 2009 13:19:56 +0200 + +python2.6 (2.6.2-3) experimental; urgency=low + + * Update to 20090919, taken from the 2.6 release branch. + * Add a conflict to python-setuptools (<< 0.6c9-3), C extension + builds broken. + * Add new symbols for update from the branch. + + -- Matthias Klose Sat, 19 Sep 2009 10:36:34 +0200 + +python2.6 (2.6.2-2) experimental; urgency=low + + * Symbol _Py_force_double@Base is i386 only. Closes: #534208. + + -- Matthias Klose Tue, 23 Jun 2009 06:14:40 +0200 + +python2.6 (2.6.2-1) experimental; urgency=low + + * Final Python 2.6.2 release. + - Update Doc/tools/sphinxext/download.html. Closes: #526797. + * Update to 20090621, taken from the 2.6 release branch. + + * Address issues when working with PYTHONUSERBASE and non standard prefix + (pointed out by Larry Hastings): + - distutils.sysconfig.get_python_lib(): Only return ".../dist-packages" if + prefix is the default prefix and if PYTHONUSERBASE is not set in the + environment. + - site.addusersitepackages(): Add USER_BASE/.../dist-packages to sys.path. + * Always use the `unix_prefix' scheme for setup.py install in a virtualenv + setup. LP: #339904. + * Don't make the setup.py install options --install-layout=deb and --prefix + conflict with each other. + * distutils: Always install into `/usr/local/lib/python2.6/dist-packages' + if an option `--prefix=/usr/local' is present (except for virtualenv + and PYTHONUSERBASE installations). LP: #362570. + * Always use `site-packages' as site directory name in virtualenv. + + * Do not add /usr/lib/pythonXY.zip on sys.path. + * Add symbols files for libpython2.6 and python2.6-dbg, don't include symbols + from builtins, which can either be built as builtins or extensions. + * Keep an empty lib-dynload in python2.6-minimal to avoid a warning on + startup. + * Build a shared library configured --with-pydebug. LP: #322580. + * Fix some lintian warnings. + * Use the information in /etc/lsb-release for platform.dist(). LP: #196526. + * Move the bdist_wininst files into the -dev package (only needed to build + windows installers). + * Document changes to the site directory name in the installation manual. + * Fix issue #1113244: Py_XINCREF, Py_DECREF, Py_XDECREF: Add + `do { ... } while (0)' to avoid compiler warnings. Closes: #516956. + * debian/pyhtml2devhelp.py: update for python 2.6 (Marc Deslauriers). + * debian/rules: re-enable documentation files for devhelp. LP: #338791. + * python2.6-doc: Depend on libjs-jquery, use jquery.js from this package. + Closes: #523482. + + -- Matthias Klose Sun, 21 Jun 2009 16:12:15 +0200 + +python2.6 (2.6.1-3) experimental; urgency=low + + * Update to 20090318, taken from the 2.6 release branch. + * Use the information in /etc/lsb-release for platform.dist(). + * Update installation schemes: LP: #338395. Closes: #520278. + - When the --prefix option is used for setup.py install, Use the + `unix_prefix' scheme. + - Use the `deb_system' scheme if --install-layout=deb is specified. + - Use the the `unix_local' scheme if neither --install-layout=deb + nor --prefix is specified. + - The options --install-layout=deb and --prefix are exclusive. + * Don't fail installation/removal if directories in /usr/local cannot + be created. LP: #338227. + * Don't try to move away the site-packages directory. There never was a + python2.6 upload using site-packages. Closes: #518780. + * Fix build failure on mips/mipsel. Closes: #519386. + + -- Matthias Klose Wed, 18 Mar 2009 22:17:20 +0100 + +python2.6 (2.6.1-2) experimental; urgency=low + + * Move libpython2.6.a into the python2.6-dev package. + * Move idlelib into the idle-python2.6 package. + + -- Matthias Klose Wed, 25 Feb 2009 18:42:19 +0100 + +python2.6 (2.6.1-1) experimental; urgency=low + + * New upstream version, upload to experimental. + * Update to 20090225, taken from the 2.6 release branch. + * Don't build-depend on locales on armel, hppa, ia64 and mipsel; package is + currently not installable. + + -- Matthias Klose Wed, 25 Feb 2009 18:42:19 +0100 + +python2.6 (2.6.1-0ubuntu9) jaunty; urgency=low + + * Don't build pyexpat, _elementtree and _ctypes as builtin extensions, + third party packages make too many assumptions about these not built + as builtins. + + -- Matthias Klose Tue, 24 Feb 2009 16:34:27 +0100 + +python2.6 (2.6.1-0ubuntu8) jaunty; urgency=low + + * Link the shared libpython with $(MODLIBS). + + -- Matthias Klose Sun, 22 Feb 2009 16:38:49 +0100 + +python2.6 (2.6.1-0ubuntu7) jaunty; urgency=low + + * Update to 20090222, taken from the 2.6 release branch. + + -- Matthias Klose Sun, 22 Feb 2009 10:35:29 +0100 + +python2.6 (2.6.1-0ubuntu6) jaunty; urgency=low + + * Don't build the gdbm extension from the python2.6 source. + * Build the dbm extension using libdb. + * Don't build-depend on locales on sparc (currently not installable), only + needed by the testsuite. + * Update to 20090219, taken from the 2.6 release branch. + + -- Matthias Klose Thu, 19 Feb 2009 12:43:20 +0100 + +python2.6 (2.6.1-0ubuntu5) jaunty; urgency=low + + * Add build dependency on libdb-dev. + + -- Matthias Klose Mon, 16 Feb 2009 13:34:41 +0100 + +python2.6 (2.6.1-0ubuntu4) jaunty; urgency=low + + * Disable the profiled build on all architectures. + + -- Matthias Klose Mon, 16 Feb 2009 11:18:51 +0100 + +python2.6 (2.6.1-0ubuntu3) jaunty; urgency=low + + * Disable the profiled build on armel as well. + + -- Matthias Klose Sun, 15 Feb 2009 10:38:02 +0100 + +python2.6 (2.6.1-0ubuntu2) jaunty; urgency=low + + * Don't use the profiled build on amd64, lpia and sparc (GCC + PR profile/38292). + + -- Matthias Klose Sat, 14 Feb 2009 14:09:34 +0100 + +python2.6 (2.6.1-0ubuntu1) jaunty; urgency=low + + * Update to 20090211, taken from the 2.6 release branch. + + -- Matthias Klose Fri, 13 Feb 2009 12:51:00 +0100 + +python2.6 (2.6.1-0ubuntu1~ppa1) jaunty; urgency=low + + * Python 2.6.1 release. + * Update to 20081206, taken from the 2.6 release branch. + * Ensure that all extensions from the -minimal package are statically + linked into the interpreter. + * Include expat, _elementtree, datetime, bisect, _bytesio, _locale, + _fileio in -minimal to link these extensions statically. + + -- Matthias Klose Fri, 05 Dec 2008 20:43:51 +0100 + +python2.6 (2.6-0ubuntu1~ppa5) intrepid; urgency=low + + * Test build + + -- Matthias Klose Fri, 14 Nov 2008 10:14:38 +0100 + +python2.6 (2.6-0ubuntu1~ppa4) intrepid; urgency=low + + * Do not build the bsddb3 module from this source, but recommend the + python-bsddb3 package (will be a dependency after python-bsddb3 is in + the archive). + * For locally installed packages, create a directory + /usr/local/lib/python2.6/dist-packages. This is the default for + installations done with distutils and setuptools. Third party stuff + packaged within the distribution goes to /usr/lib/python2.6/dist-packages. + There is no /usr/lib/python2.6/site-packages in the file system and + on sys.path. No package within the distribution must not install + anything in this location. + * Place the gdbm extension into the python2.6 package. + * distutils: Add an option --install-layout=deb, which + - installs into $prefix/dist-packages instead of $prefix/site-packages. + - doesn't encode the python version into the egg name. + + -- Matthias Klose Sat, 25 Oct 2008 11:12:24 +0000 + +python2.6 (2.6-0ubuntu1~ppa3) intrepid; urgency=low + + * Build-depend on libdb4.6-dev, instead of libdb-dev (4.7). Test suite + hangs in the bsddb tests. + + -- Matthias Klose Wed, 22 Oct 2008 11:05:13 +0200 + +python2.6 (2.6-0ubuntu1~ppa2) intrepid; urgency=low + + * Update to 20081021, taken from the 2.6 release branch. + * Fix typos and section names in doc-base files. LP: #273344. + * Build a new package libpython2.6. + * For locally installed packages, create a directory + /usr/local/lib/python2.6/system-site-packages, which is symlinked + from /usr/lib/python2.6/site-packages. Third party stuff packaged + within the distribution goes to /usr/lib/python2.6/dist-packages. + + -- Matthias Klose Tue, 21 Oct 2008 18:09:31 +0200 + +python2.6 (2.6-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 release. + * Update to current branch 20081009. + + -- Matthias Klose Thu, 09 Oct 2008 14:28:26 +0200 + +python2.6 (2.6~b3-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta3 release. + + -- Matthias Klose Sun, 24 Aug 2008 01:34:54 +0000 + +python2.6 (2.6~b2-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta2 release. + + -- Matthias Klose Thu, 07 Aug 2008 16:45:56 +0200 + +python2.6 (2.6~b1-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta1 release. + + -- Matthias Klose Tue, 15 Jul 2008 12:57:20 +0000 + +python2.6 (2.6~a3-0ubuntu1~ppa2) hardy; urgency=low + + * Test build + + -- Matthias Klose Thu, 29 May 2008 18:08:48 +0200 + +python2.6 (2.6~a3-0ubuntu1~ppa1) hardy; urgency=low + + * Python 2.6 alpha3 release. + * Update to current trunk 20080523. + + -- Matthias Klose Thu, 22 May 2008 17:37:46 +0200 + +python2.5 (2.5.2-5) unstable; urgency=low + + * Backport new function signal.set_wakeup_fd from the trunk. + Background: http://bugzilla.gnome.org/show_bug.cgi?id=481569 + + -- Matthias Klose Wed, 30 Apr 2008 12:05:10 +0000 + +python2.5 (2.5.2-4) unstable; urgency=low + + * Update to 20080427, taken from the 2.5 release branch. + - Fix issues #2670, #2682. + * Disable running pybench on the hppa buildd (ftbfs). + * Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, + CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + * Support parallel= in DEB_BUILD_OPTIONS (see #209008). + + -- Matthias Klose Sun, 27 Apr 2008 10:40:51 +0200 + +python2.5 (2.5.2-3) unstable; urgency=medium + + * Update to 20080416, taken from the 2.5 release branch. + - Fix CVE-2008-1721, integer signedness error in the zlib extension module. + - Fix urllib2 file descriptor happens byte-at-a-time, reverting + a fix for excessively large memory allocations when calling .read() + on a socket object wrapped with makefile(). + * Disable some regression tests on some architectures: + - arm: test_compiler, test_ctypes. + - armel: test_compiler. + - hppa: test_fork1, test_wait3. + - m68k: test_bsddb3, test_compiler. + * Build-depend on libffi-dev instead of libffi4-dev. + * Fix CVE-2008-1679, integer overflows in the imageop module. + + -- Matthias Klose Wed, 16 Apr 2008 23:37:46 +0200 + +python2.5 (2.5.2-2) unstable; urgency=low + + * Use site.addsitedir() to add directories in /usr/local to sys.path. + Addresses: #469157, #469818. + + -- Matthias Klose Sat, 08 Mar 2008 16:11:23 +0100 + +python2.5 (2.5.2-1) unstable; urgency=low + + * Python 2.5.2 release. + * Merge from Ubuntu: + - Move site customization into sitecustomize.py, don't make site.py + a config file. Addresses: #309719, #413172, #457361. + - Move site.py to python2.4-minimal, remove `addbuilddir' from site.py, + which is unnecessary for installed builds. + - python2.5-dev: Recommend libc-dev instead of suggesting it. LP: #164909. + - Fix issue 961805, Tk Text.edit_modified() fails. LP: #84720. + + -- Matthias Klose Thu, 28 Feb 2008 23:18:52 +0100 + +python2.5 (2.5.1-7) unstable; urgency=low + + * Update to 20080209, taken from the 2.5 release branch. + * Build the _bsddb extension with db-4.5 again; 4.6 is seriously + broken when used with the _bsddb extension. + * Do not run pybench on arm and armel. + * python2.5: Provide python2.5-wsgiref. + * Fix a pseudo RC report with duplicated attributes in the control + file. Closes: #464307. + + -- Matthias Klose Sun, 10 Feb 2008 00:22:57 +0100 + +python2.5 (2.5.1-6) unstable; urgency=low + + * Update to 20080102, taken from the 2.5 release branch. + - Only define _BSD_SOURCE on OpenBSD systems. Closes: #455400. + * Fix handling of packages in linecache.py (Kevin Goodsell). LP: #70902. + * Bump debhelper to v5. + * Register binfmt for .py[co] files. + * Use absolute paths when byte-compiling files. Addresses: #453346. + Closes: #413566, LP: #177722. + * CVE-2007-4965, http://bugs.python.org/issue1179: + Multiple integer overflows in the imageop module in Python 2.5.1 and + earlier allow context-dependent attackers to cause a denial of service + (application crash) and possibly obtain sensitive information (memory + contents) via crafted arguments to (1) the tovideo method, and unspecified + other vectors related to (2) imageop.c, (3) rbgimgmodule.c, and other + files, which trigger heap-based buffer overflows. + Patch prepared by Stephan Herrmann. Closes: #443333, LP: #163845. + * Register info docs when doing source only uploads. LP: #174786. + * Remove deprecated value from categories in desktop file. LP: #172874. + * python2.5-dbg: Don't include the gdbm and _tkinter extensions, now provided + in separate packages. + * Provide a symlink changelog -> NEWS. Closes: #439271. + * Fix build failure on hurd, working around poll() on systems on which it + returns an error on invalid FDs. Closes: #438914. + * Configure --with-system-ffi on all architectures. Closes: #448520. + * Fix version numbers in copyright and README files (Dan O'Huiginn). + Closes: #446682. + * Move some documents from python2.5 to python2.5-dev. + + -- Matthias Klose Wed, 02 Jan 2008 22:22:19 +0100 + +python2.5 (2.5.1-5) unstable; urgency=low + + * Build the _bsddb extension with db-4.6. + + -- Matthias Klose Fri, 17 Aug 2007 00:39:35 +0200 + +python2.5 (2.5.1-4) unstable; urgency=low + + * Update to 20070813, taken from the 2.5 release branch. + * Include plat-mac/plistlib.py (plat-mac is not in sys.path by default. + Closes: #435826. + * Use emacs22 to build the documentation in info format. Closes: #434969. + * Build-depend on db-dev (>= 4.6). Closes: #434965. + + -- Matthias Klose Mon, 13 Aug 2007 22:22:44 +0200 + +python2.5 (2.5.1-3) unstable; urgency=high + + * Support mixed-endian IEEE floating point, as found in the ARM old-ABI + (Aurelien Jarno). Closes: #434905. + + -- Matthias Klose Fri, 27 Jul 2007 20:01:35 +0200 + +python2.5 (2.5.1-2) unstable; urgency=low + + * Update to 20070717, taken from the 2.5 release branch. + * Fix reference count for sys.pydebug variable. Addresses: #431393. + * Build depend on libbluetooth-dev instead of libbluetooth2-dev. + + -- Matthias Klose Tue, 17 Jul 2007 14:09:47 +0200 + +python2.5 (2.5.1-1) unstable; urgency=low + + * Python-2.5.1 release. + * Build-depend on gcc-4.1 (>= 4.1.2-4) on alpha, powerpc, s390, sparc. + * Merge from Ubuntu: + - Add debian/patches/subprocess-eintr-safety.dpatch (LP: #87292): + - Create and use wrappers around read(), write(), and os.waitpid() in the + subprocess module which retry the operation on an EINTR (which happens + if e. g. an alarm was raised while the system call was in progress). + It is incredibly hard and inconvenient to sensibly handle this in + applications, so let's fix this at the right level. + - Patch based on original proposal of Peter <85>strand + in http://python.org/sf/1068268. + - Add two test cases. + - Change the interpreter to build and install python extensions + built with the python-dbg interpreter with a different name into + the same path (by appending `_d' to the extension name). The debug build + of the interpreter tries to first load a foo_d.so or foomodule_d.so + extension, then tries again with the normal name. + - When trying to import the profile and pstats modules, don't + exit, add a hint to the exception pointing to the python-profiler + package, don't exit. + - Keep the module version in the .egg-info name, only remove the + python version. + - python2.5-dbg: Install Misc/SpecialBuilds.txt, document the + debug changes in README.debug. + * Update to 20070425, taken from the 2.5 release branch. + + -- Matthias Klose Wed, 25 Apr 2007 22:12:50 +0200 + +python2.5 (2.5-6) unstable; urgency=medium + + * webbrowser.py: Recognize other browsers: www-browser, x-www-browser, + iceweasel, iceape. + * Move pyconfig.h from the python2.5-dev into the python2.5 package; + required by builds for pure python modules without having python2.5-dev + installed (matching the functionality in python2.4). + * Move the unicodedata module into python2.5-minimal; allows byte compilation + of UTF8 encoded files. + * Do not install anymore outdated debhelper sample scripts. + * Install Misc/SpecialBuilds.txt as python2.5-dbg document. + + -- Matthias Klose Wed, 21 Feb 2007 01:17:12 +0100 + +python2.5 (2.5-5) unstable; urgency=high + + * Do not run the python benchmark on m68k. Timer problems. + Fixes FTBFS on m68k. + * Update to 20061209, taken from the 2.5 release branch. + - Fixes building the library reference in info format. + + -- Matthias Klose Sat, 9 Dec 2006 13:40:48 +0100 + +python2.5 (2.5-4) unstable; urgency=medium + + * Update to 20061203, taken from the 2.5 release branch. + - Fixes build failures on knetfreebsd and the hurd. Closes: #397000. + * Clarify README about distutils. Closes: #396394. + * Move python2.5-config to python2.5-dev. Closes: #401451. + * Cleanup build-conflicts. Addresses: #394512. + + -- Matthias Klose Sun, 3 Dec 2006 18:22:49 +0100 + +python2.5 (2.5-3.1) unstable; urgency=low + + * Non-maintainer upload. + * python2.5-minimal depends on python-minimal (>= 2.4.4-1) because it's the + first version which lists python2.5 as an unsupported runtime (ie a + runtime that is available but for which modules are not auto-compiled). + And being listed there is required for python-central to accept the + installation of python2.5-minimal. Closes: #397006 + + -- Raphael Hertzog Wed, 22 Nov 2006 15:41:06 +0100 + +python2.5 (2.5-3) unstable; urgency=medium + + * Update to 20061029 (2.4.4 was released on 20061019), taken from + the 2.5 release branch. We do not want to have regressions in + 2.5 compared to the 2.4.4 release. + * Don't run pybench on m68k, fails in the calibration loop. Closes: #391030. + * Run the installation/removal hooks. Closes: #383292, #391036. + + -- Matthias Klose Sun, 29 Oct 2006 11:35:19 +0100 + +python2.5 (2.5-2) unstable; urgency=medium + + * Update to 20061003, taken from the 2.5 release branch. + * On arm and m68k, don't run the pybench in debug mode. + * Fix building the source within exec_prefix (Alexander Wirt). + Closes: #385336. + + -- Matthias Klose Tue, 3 Oct 2006 10:08:36 +0200 + +python2.5 (2.5-1) unstable; urgency=low + + * Python 2.5 release. + * Update to 20060926, taken from the 2.5 release branch. + * Run the Python benchmark during the build, compare the results + of the static and shared builds. + * Fix invalid html in python2.5.devhelp.gz. + * Add a python2.5 console entry to the menu (hidden by default). + * python2.5: Suggest python-profiler. + + -- Matthias Klose Tue, 26 Sep 2006 02:36:11 +0200 + +python2.5 (2.5~c1-1) unstable; urgency=low + + * Python 2.5 release candidate 1. + * Update to trunk 20060818. + + -- Matthias Klose Sat, 19 Aug 2006 19:21:05 +0200 + +python2.5 (2.5~b3-1) unstable; urgency=low + + * Build the _ctypes module for m68k-linux. + + -- Matthias Klose Fri, 11 Aug 2006 18:19:19 +0000 + +python2.5 (2.5~b3-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta3 release. + * Update to trunk 20060811. + * Rebuild the documentation. + * Fix value of sys.exec_prefix in the debug build. + * Do not build the library reference in info format; fails to build. + * Link the interpreter against the shared runtime library. With + gcc-4.1 the difference in the pystones benchmark dropped from about + 12% to about 6%. + * Install the statically linked version of the interpreter as + python2.5-static for now. + * Link the shared libpython with -O1. + + -- Matthias Klose Thu, 10 Aug 2006 14:04:48 +0000 + +python2.5 (2.4.3+2.5b2-3) unstable; urgency=low + + * Disable the testsuite on s390; don't care about "minimally configured" + buildd's. + + -- Matthias Klose Sun, 23 Jul 2006 11:45:03 +0200 + +python2.5 (2.4.3+2.5b2-2) unstable; urgency=low + + * Update to trunk 20060722. + * Merge idle-lib from idle-python2.5 into python2.5. + * Merge lib-tk from python-tk into python2.5. + * Tkinter.py: Suggest installation of python-tk package on failed + import of the _tkinter extension. + * Don't run the testsuite for the debug build on alpha. + * Don't run the test_compiler test on m68k. Just takes too long. + * Disable building ctypes on m68k (requires support for closures). + + -- Matthias Klose Sat, 22 Jul 2006 22:26:42 +0200 + +python2.5 (2.4.3+2.5b2-1) unstable; urgency=low + + * Python 2.5 beta2 release. + * Update to trunk 20060716. + * When built on a buildd, do not run the following test which try to + access the network: test_codecmaps_cn, test_codecmaps_hk, test_codecmaps_jp, + test_codecmaps_kr, test_codecmaps_tw, test_normalization. + * When built on a buildd, do not run tests requiring missing write permissions: + test_ossaudiodev. + + -- Matthias Klose Sun, 16 Jul 2006 02:53:50 +0000 + +python2.5 (2.4.3+2.5b2-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta2 release. + + -- Matthias Klose Thu, 13 Jul 2006 17:16:52 +0000 + +python2.5 (2.4.3+2.5b1-1ubuntu2) edgy; urgency=low + + * Fix python-dev dependencies. + * Update to trunk 20060709. + + -- Matthias Klose Sun, 9 Jul 2006 18:50:32 +0200 + +python2.5 (2.4.3+2.5b1-1ubuntu1) edgy; urgency=low + + * Python 2.5 beta1 release. + * Update to trunk 20060623. + * Merge changes from the python2.4 packages. + * python2.5-minimal: Add _struct. + + -- Matthias Klose Fri, 23 Jun 2006 16:04:46 +0200 + +python2.5 (2.4.3+2.5a1-1) experimental; urgency=low + + * Update to trunk 20060409. + * Run testsuite for debug build as well. + * Build-depend on gcc-4.1. + + -- Matthias Klose Sun, 9 Apr 2006 22:27:05 +0200 + +python2.5 (2.4.3+2.5a1-0ubuntu1) dapper; urgency=low + + * Python 2.5 alpha1 release. + * Drop integrated patches. + * Add build dependencies on libsqlite3-dev and libffi4-dev. + * Add (build-)dependency on mime-support, libgpmg1 (test suite). + * Build using the system FFI. + * python2.5 provides python2.5-ctypes and python2.5-pysqlite2, + python2.5-elementtree. + * Move hashlib.py to python-minimal. + * Lib/hotshot/pstats.py: Error out on missing profile/pstats modules. + + -- Matthias Klose Wed, 5 Apr 2006 14:56:15 +0200 + +python2.4 (2.4.3-8ubuntu1) edgy; urgency=low + + * Resynchronize with Debian unstable. Remaining changes: + - Apply langpack-gettext patch. + - diff.gz contains pregenerated html and info docs. + - Build the -doc package from this source. + + -- Matthias Klose Thu, 22 Jun 2006 18:39:57 +0200 + +python2.4 (2.4.3-8) unstable; urgency=low + + * Remove python2.4's dependency on python-central. On installation of + the runtime, call hooks /usr/share/python/runtime.d/*.rtinstall. + On removal, call hooks /usr/share/python/runtime.d/*.rtremove. + Addresses: #372658. + * Call the rtinstall hooks only, if it's a new installation, or the first + installation using the hooks. Adresses: #373677. + + -- Matthias Klose Sun, 18 Jun 2006 00:56:13 +0200 + +python2.4 (2.4.3-7) unstable; urgency=medium + + * Reupload, depend on python-central (>= 0.4.15). + * Add build-conflict on python-xml. + + -- Matthias Klose Wed, 14 Jun 2006 18:56:57 +0200 + +python2.4 (2.4.3-6) medium; urgency=low + + * idle-python2.4: Remove the old postinst and prerm scripts. + * Name the runtime correctly in python2.4-minimal's installation + scripts. + + -- Matthias Klose Mon, 12 Jun 2006 17:39:56 +0000 + +python2.4 (2.4.3-5) unstable; urgency=low + + * python2.4-prerm: Handle the case, when python-central is not installed. + * idle-python2.4: Depend on python-tk instead of python2.4-tk. + + -- Matthias Klose Fri, 9 Jun 2006 05:17:17 +0200 + +python2.4 (2.4.3-4) unstable; urgency=low + + * SVN update up to 2006-06-07 + * Use python-central. + * Don't build the -tk and -gdbm packages from this source; now built + from the python-stdlib-extensions source. + * Remove leftover build dependency on libgmp3-dev. + * Do not build-depend on libbluetooth1-dev and libgpmg1-dev on + hurd-i386, kfreebsd-i386, kfreebsd-amd64. Closes: #365830. + * Do not run the test_tcl test; hangs for unknown reasons on at least + the following buildds: vivaldi(m68k), goedel (alpha), mayer (mipsel). + And no virtual package to file bug reports for the buildds ... + Closes: #364419. + * Move the Makefile from python2.4-dev to python2.4. Closes: #366473. + * Fix typo in pdb(1). Closes: #365772. + * New autoconf likes the mandir in /usr/share instead of /usr; work + with both locations. Closes: #367618. + + -- Matthias Klose Wed, 7 Jun 2006 21:37:20 +0200 + +python2.4 (2.4.3-3) unstable; urgency=low + + * SVN update up to 2006-04-21 + * Update locale aliases from /usr/share/X11/locale/locale.alias. + * Start idle with option -n from the desktop menu, so that the program + can be started in parallel. + * Testsuite related changes only: + - Add build dependencies mime-support, libgpmg1 (needed by test cases). + - Run the testsuite with bsddb, audio and curses resources enabled. + - Re-run the failed tests in verbose mode. + - Run the test suite for the debug build as well. + - Build depend on netbase, needed by test_socketmodule. + - Build depend on libgpmg1, needed by test_curses. + - On the buildds do not run the tests needing the network resource. + * Update python logo. + * Check for the availability of the profile and pstats modules when + importing hotshot.pstats. Closes: #334067. + * Don't build the -doc package from the python2.4 source. + * Set OPT in the installed Makefile to -O2. + + -- Matthias Klose Fri, 21 Apr 2006 19:58:43 +0200 + +python2.4 (2.4.3-2) unstable; urgency=low + + * Add (build-)dependency on mime-support. + + -- Matthias Klose Tue, 4 Apr 2006 22:21:41 +0200 + +python2.4 (2.4.3-1) unstable; urgency=low + + * Python 2.4.3 release. + + -- Matthias Klose Thu, 30 Mar 2006 23:42:37 +0200 + +python2.4 (2.4.3-0ubuntu1) dapper; urgency=low + + * Python 2.4.3 release. + - Fixed a bug that the gb18030 codec raises RuntimeError on encoding + surrogate pair area on UCS4 build. Ubuntu: #29289. + + -- Matthias Klose Thu, 30 Mar 2006 10:57:32 +0200 + +python2.4 (2.4.2+2.4.3c1-0ubuntu1) dapper; urgency=low + + * SVN update up to 2006-03-25 (2.4.3 candidate 1). + - Regenerate the documentation. + + -- Matthias Klose Mon, 27 Mar 2006 12:03:05 +0000 + +python2.4 (2.4.2-1ubuntu3) dapper; urgency=low + + * SVN update up to 2006-03-04 + - Regenerate the documentation. + - map.mmap(-1, size, ...) can return anonymous memory again on Unix. + Ubuntu #26201. + * Build-depend on libncursesw5-dev, ncursesw5 is preferred for linking. + Provides UTF-8 compliant curses bindings. + * Fix difflib where certain patterns of differences were making difflib + touch the recursion limit. + + -- Matthias Klose Sat, 4 Mar 2006 21:38:24 +0000 + +python2.4 (2.4.2-1ubuntu2) dapper; urgency=low + + * SVN update up to 2006-01-17 + - pwd is now a builtin module, remove it from python-minimal. + - Regenerate the documentation. + * python2.4-tk: Suggest tix instead of tix8.1. + * Move config/Makefile from the -dev package into the runtime package + to be able to use the bdist_wininst distutils command. Closes: #348335. + + -- Matthias Klose Tue, 17 Jan 2006 11:02:24 +0000 + +python2.4 (2.4.2-1ubuntu1) dapper; urgency=low + + * Temporarily remove build dependency on lsb-release. + + -- Matthias Klose Sun, 20 Nov 2005 17:40:18 +0100 + +python2.4 (2.4.2-1build1) dapper; urgency=low + + * Rebuild (openssl-0.9.8). + + -- Matthias Klose Sun, 20 Nov 2005 15:27:24 +0000 + +python2.4 (2.4.2-1) unstable; urgency=low + + * Python 2.4.2 release. + + -- Matthias Klose Thu, 29 Sep 2005 01:49:28 +0200 + +python2.4 (2.4.1+2.4.2rc1-1) unstable; urgency=low + + * Python 2.4.2 release candidate 1. + * Fix "Fatal Python error" from cStringIO's writelines. + Patch by Andrew Bennetts. + + -- Matthias Klose Thu, 22 Sep 2005 10:33:22 +0200 + +python2.4 (2.4.1-5) unstable; urgency=low + + * CVS update up to 2005-09-14 + - Regenerate the html and info docs. + * Add some more locale aliases. + * Fix substitution pf python version in README.python2.4-minimal. + Closes: #327487. + * On m68k, build using -O2 (closes: #326903). + * On Debian, don't configure --with-fpectl, which stopped working with + glibc-2.3.5. + + -- Matthias Klose Wed, 14 Sep 2005 17:32:56 +0200 + +python2.4 (2.4.1-4) unstable; urgency=low + + * CVS update up to 2005-09-04 + - teTeX 3.0 related fixes (closes: #322407). + - Regenerate the html and info docs. + * Add entry for IDLE in the Gnome menus. + * Don't build-depend on libbluetooth-dev on the Hurd (closes: #307037). + * Reenable the cthreads patch for the Hurd (closes: #307052). + + -- Matthias Klose Sun, 4 Sep 2005 18:31:42 +0200 + +python2.4 (2.4.1-3) unstable; urgency=low + + * Synchronise with Ubuntu: + - Build a python2.4-minimal package. + + -- Matthias Klose Tue, 12 Jul 2005 00:23:10 +0000 + +python2.4 (2.4.1-2ubuntu3) breezy; urgency=low + + * CVS update up to 2005-07-07 + * Regenerate the documentation. + + -- Matthias Klose Thu, 7 Jul 2005 09:21:28 +0200 + +python2.4 (2.4.1-2ubuntu2) breezy; urgency=low + + * CVS update up to 2005-06-15 + * Regenerate the documentation. + * Synchronize with Debian. Ubuntu 10485. + * idle-python2.4 enhances python2.4. Ubuntu 11562. + * README.Debian: Fix reference to the doc directory (closes: #311677). + + -- Matthias Klose Wed, 15 Jun 2005 08:56:57 +0200 + +python2.4 (2.4.1-2ubuntu1) breezy; urgency=low + + * Update build dependencies: + db4.2-dev -> db4.3-dev, + libreadline4-dev -> libreadline5-dev. + * python2.4-dev: Add missing templates to generate HTML docs. Ubuntu 11531. + + -- Matthias Klose Sun, 29 May 2005 00:01:05 +0200 + +python2.4 (2.4.1-2) unstable; urgency=low + + * Add the debug symbols for the python2.4, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. + * Add gdbinit example to doc directory. + + -- Matthias Klose Thu, 5 May 2005 11:12:32 +0200 + +python2.4 (2.4.1-1ubuntu2) breezy; urgency=low + + * Add the debug symbols for the python2.4, python2.4-minimal, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. Ubuntu 10261, + * Add gdbinit example to doc directory. + * For os.utime, use utimes(2), correctly working with glibc-2.3.5. + Ubuntu 10294. + + -- Matthias Klose Thu, 5 May 2005 09:06:07 +0200 + +python2.4 (2.4.1-1ubuntu1) breezy; urgency=low + + * Reupload as 2.4.1-1ubuntu1. + + -- Matthias Klose Thu, 14 Apr 2005 10:46:32 +0200 + +python2.4 (2.4.1-1) unstable; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 19:42:03 +0200 + +python2.4 (2.4.1-0) hoary; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 16:35:34 +0200 + +python2.4 (2.4+2.4.1rc2-2) unstable; urgency=low + + * Add the valgrind support file to /etc/python2.4 + * Build the -dbg package with -DPy_USING_MEMORY_DEBUGGER. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * Fix two typos in python(1). Addresses: #300124. + + -- Matthias Klose Sat, 19 Mar 2005 21:50:14 +0100 + +python2.4 (2.4+2.4.1rc2-1) unstable; urgency=low + + * Python 2.4.1 release candidate 2. + * Build-depend on libbluetooth1-dev. + + -- Matthias Klose Sat, 19 Mar 2005 00:57:14 +0100 + +python2.4 (2.4dfsg-2) unstable; urgency=low + + * CVS update up to 2005-03-03 + + -- Matthias Klose Thu, 3 Mar 2005 22:22:16 +0100 + +python2.4 (2.4dfsg-1ubuntu4) hoary; urgency=medium + + * Move exception finalisation later in the shutdown process - this + fixes the crash seen in bug #1165761, taken from CVS. + * codecs.StreamReader: Reset codec when seeking. Ubuntu #6972. + * Apply fix for SF1124295, fixing an obscure bit of Zope's security machinery. + * distutils: Don't add standard library dirs to library_dirs + and runtime_library_dirs. On amd64, runtime paths pointing to /usr/lib64 + aren't recognized by dpkg-shlibdeps, and the packages containing these + libraries aren't added to ${shlibs:Depends}. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * os.py: Avoid using items() in environ.update(). Fixes #1124513. + * Python/pythonrun.c: + * Build depend on locales, generate the locales needed for the + testsuite. + * Add build dependency on libbluetooth1-dev, adding some bluetooth + functionality to the socket module. + * Lib/test/test_sundry.py: Don't fail on import of profile & pstats, + which are separated out to the python-profiler package. + * Fix typos in manpage. + + -- Matthias Klose Tue, 29 Mar 2005 13:35:53 +0200 + + +python2.4 (2.4dfsg-1ubuntu3) hoary; urgency=low + + * debian/patches/langpack-gettext.dpatch: + - langpack support for python-gettext added + + -- Michael Vogt Tue, 1 Mar 2005 13:13:36 +0100 + +python2.4 (2.4dfsg-1ubuntu2) hoary; urgency=low + + * Revert 'essential' status on python2.4-minimal. This status on + on python-minimal is sufficient (Ubuntu #6392). + + -- Matthias Klose Wed, 9 Feb 2005 23:09:42 +0100 + +python2.4 (2.4dfsg-1ubuntu1) hoary; urgency=low + + * Resyncronise with Debian. + * Mark the python2.4-minimal package as 'essential'. + + -- Matthias Klose Wed, 9 Feb 2005 13:31:09 +0100 + +python2.4 (2.4dfsg-1) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Remove the profile.py and pstats.py modules from the source package, + not having a DFSG conforming license. The modules can be found in + the python2.x-profile package in the non-free section. + Addresses: #293932. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7ubuntu1) hoary; urgency=low + + * Fix the name of the python-dbg man page. + * Resyncronise with Debian. + * Move more modules to -minimal (new code in copy.py requires these): + dis, inspect, opcode, token, tokenize. + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-6) unstable; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Apply the pydebug-path patch. The package was already built in -5. + + -- Matthias Klose Fri, 4 Feb 2005 22:15:13 +0100 + +python2.4 (2.4-5) unstable; urgency=high + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + * CVS updates of the release24-maint branch upto 2005-02-04. + + -- Matthias Klose Fri, 4 Feb 2005 08:12:10 +0100 + +python2.4 (2.4-4) unstable; urgency=medium + + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Remove /usr/bin/smtpd.py (closes: #291049). + + -- Matthias Klose Mon, 17 Jan 2005 23:54:37 +0100 + +python2.4 (2.4-3ubuntu6) hoary; urgency=low + + * Use old-style dpatches instead of dpatch-run. + + -- Tollef Fog Heen Mon, 7 Feb 2005 15:58:05 +0100 + +python2.4 (2.4-3ubuntu5) hoary; urgency=low + + * Actually apply the patch as well (add to list of patches in + debian/rules) + + -- Tollef Fog Heen Sun, 6 Feb 2005 15:12:58 +0100 + +python2.4 (2.4-3ubuntu4) hoary; urgency=low + + * Add nb_NO and nn_NO locales to Lib/locale.py + + -- Tollef Fog Heen Sun, 6 Feb 2005 14:33:05 +0100 + +python2.4 (2.4-3ubuntu3) hoary; urgency=low + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + + -- Matthias Klose Wed, 2 Feb 2005 09:08:20 +0000 + +python2.4 (2.4-3ubuntu2) hoary; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Add operator and copy to the -minimal package. + + -- Matthias Klose Mon, 17 Jan 2005 23:19:47 +0100 + +python2.4 (2.4-3ubuntu1) hoary; urgency=low + + * Resynchronise with Debian. + * python2.4: Depend on the very same version of python2.4-minimal. + * Docment, that time.strptime currently cannot be used, if the + python-minimal package is installed without the python package. + + -- Matthias Klose Sun, 9 Jan 2005 19:35:48 +0100 + +python2.4 (2.4-3) unstable; urgency=medium + + * Build the fpectl module. + * Updated to CVS release24-maint 20050107. + + -- Matthias Klose Sat, 8 Jan 2005 19:05:21 +0100 + +python2.4 (2.4-2ubuntu5) hoary; urgency=low + + * Updated to CVS release24-maint 20050102. + * python-minimal: + - os.py: Use dict instead of UserDict, remove UserDict from -minimal. + - add pickle, threading, needed for subprocess module. + - optparse.py: conditionally import gettext, if not available, + define _ as the identity function. Patch taken from the trunk. + Avoids import of _locale, locale, gettext, copy, repr, itertools, + collections, token, tokenize. + - Add a build check to make sure that the minimal module list is + closed under dependency. + * Fix lintian warnings. + + -- Matthias Klose Sun, 2 Jan 2005 22:00:14 +0100 + +python2.4 (2.4-2ubuntu4) hoary; urgency=low + + * Add UserDict.py to the -minimal package, since os.py needs it. + + -- Colin Watson Thu, 30 Dec 2004 20:41:28 +0000 + +python2.4 (2.4-2ubuntu3) hoary; urgency=low + + * Add os.py and traceback.py to the -minimal package, get the list + of modules from the README. + + -- Matthias Klose Mon, 27 Dec 2004 08:20:45 +0100 + +python2.4 (2.4-2ubuntu2) hoary; urgency=low + + * Add compileall.py and py_compile.py to the -minimal package, not + just to the README ... + + -- Matthias Klose Sat, 25 Dec 2004 22:24:56 +0100 + +python2.4 (2.4-2ubuntu1) hoary; urgency=low + + * Separate the interpreter and a minimal subset of modules into + a python2.4-minimal package. See the README.Debian.gz in this + package. + * Move site.py to python2.4-minimal as well. + * Add documentation files for devhelp. + + -- Matthias Klose Sun, 19 Dec 2004 22:47:32 +0100 + +python2.4 (2.4-2) unstable; urgency=medium + + * Updated patch for #283108. Thanks to Jim Meyering. + + -- Matthias Klose Fri, 3 Dec 2004 17:00:16 +0100 + +python2.4 (2.4-1) unstable; urgency=low + + * Final 2.4 release. + * Flush stdout/stderr if closed (SF #1074011). + + -- Matthias Klose Wed, 1 Dec 2004 07:54:34 +0100 + +python2.4 (2.3.97-2) unstable; urgency=low + + * Don't run test_tcl, hanging on the buildds. + + -- Matthias Klose Fri, 19 Nov 2004 23:48:42 +0100 + +python2.4 (2.3.97-1) unstable; urgency=low + + * Python 2.4 Release Candidate 1. + + -- Matthias Klose Fri, 19 Nov 2004 21:27:02 +0100 + +python2.4 (2.3.96-1) experimental; urgency=low + + * Updated to CVS release24-maint 20041113. + * Build the docs in info format again. + + -- Matthias Klose Sat, 13 Nov 2004 21:21:10 +0100 + +python2.4 (2.3.95-2) experimental; urgency=low + + * Move distutils package from the python2.4-dev into the python2.4 + package. + + -- Matthias Klose Thu, 11 Nov 2004 22:56:14 +0100 + +python2.4 (2.3.95-1) experimental; urgency=low + + * Python 2.4 beta2 release. + + -- Matthias Klose Thu, 4 Nov 2004 23:43:47 +0100 + +python2.4 (2.3.94-1) experimental; urgency=low + + * Python 2.4 beta1 release. + + -- Matthias Klose Sat, 16 Oct 2004 08:33:57 +0200 + +python2.4 (2.3.93-1) experimental; urgency=low + + * Python 2.4 alpha3 release. + + -- Matthias Klose Fri, 3 Sep 2004 21:53:47 +0200 + +python2.4 (2.3.92-1) experimental; urgency=low + + * Python 2.4 alpha2 release. + + -- Matthias Klose Thu, 5 Aug 2004 23:53:18 +0200 + +python2.4 (2.3.91-1) experimental; urgency=low + + * Python 2.4 alpha1 release. + Highlights: http://www.python.org/2.4/highlights.html + + -- Matthias Klose Fri, 9 Jul 2004 17:38:54 +0200 + +python2.4 (2.3.90-1) experimental; urgency=low + + * Package HEAD branch (pre alpha ..). + + -- Matthias Klose Mon, 14 Jun 2004 23:19:57 +0200 + +python2.3 (2.3.4-1) unstable; urgency=medium + + * Final Python 2.3.4 Release. + * In the API docs, fix signature of PyModule_AddIntConstant (closes: #250826). + * locale.getdefaultlocale: don't fail with empty environment variables. + Closes: #249816. + * Include distutils/command/wininst.exe in -dev package (closes: #249006). + * Disable cthreads on the Hurd (Michael Banck). Closes: #247211. + * Add a note to pygettext(1), that this program is deprecated in favour + of xgettext, which now includes support for Python as well. + Closes: #246332. + + -- Matthias Klose Fri, 28 May 2004 22:59:42 +0200 + +python2.3 (2.3.3.91-1) unstable; urgency=low + + * Python 2.3.4 Release Candidate 1. + * Do not use the default namespace for attributes. Patch taken from the + 2.3 maintenance branch. + The xmllib module is obsolete. Use xml.sax instead. + * http://python.org/sf/945642 - fix nonblocking i/o with ssl socket. + + -- Matthias Klose Thu, 13 May 2004 21:24:52 +0200 + +python2.3 (2.3.3-7) unstable; urgency=low + + * Add a workaround for GNU libc nl_langinfo()'s returning NULL. + Closes: #239237. + Patch taken from 2.3 maintenance branch. + * threading.py: Remove calls to currentThread() in _Condition methods that + were side-effect. Side-effects were deemed unnecessary and were causing + problems at shutdown time when threads were catching exceptions at start + time and then triggering exceptions trying to call currentThread() after + gc'ed. Masked the initial exception which was deemed bad. + Closes: #195812. + * Properly support normalization of empty unicode strings. Closes: #239986. + Patch taken from 2.3 maintenance branch. + * README.maintainers: Add section where to find the documentation tools. + * Fix crash in pyexpat module (closes: #229281). + * For the Hurd, set the interpreters recursion limit to 930. + * Do not try to byte-compile the test files on installation; this + currently breaks the Hurd install. + + -- Matthias Klose Sat, 1 May 2004 07:50:46 +0200 + +python2.3 (2.3.3-6) unstable; urgency=low + + * Don't build the unversioned python{,-*} packages anymore. Now + built from the python-defaults package. + * Update to the proposed python-policy: byte-compile using -E. + * Remove python-elisp's dependency on emacs20 (closes: #232785). + * Don't build python-elisp from the python2.3 source anymore, + get it from python-mode.sf.net as a separate source package. + * python2.3-dev suggests libc-dev (closes: #231091). + * get LDSHARED and CCSHARED (like, CC, CXX, CPP, CFLAGS) from + the environment + * Set CXX in installed config/Makefile (closes: #230273). + + -- Matthias Klose Tue, 24 Feb 2004 07:07:51 +0100 + +python2.3 (2.3.3-5) unstable; urgency=low + + * Build-depend on libdb4.2-dev, instead of libdb4.1-dev. According + to the docs the file format is compatible. + + -- Matthias Klose Mon, 12 Jan 2004 10:37:45 +0100 + +python2.3 (2.3.3-4) unstable; urgency=low + + * Fix broken _bsddb module. setup.py picked up the wrong library. + + -- Matthias Klose Sun, 4 Jan 2004 11:30:00 +0100 + +python2.3 (2.3.3-3) unstable; urgency=low + + * Fix typo in patch (closes: #224797, #226064). + + -- Matthias Klose Sun, 4 Jan 2004 09:23:21 +0100 + +python2.3 (2.3.3-2) unstable; urgency=medium + + * Lib/email/Charset: use locale unaware function to lower case of locale + name (closes: #224797). + * Update python-mode to version from python-mode.sf.net. Fixes highlighting + problems (closes: #223520). + * Backport from mainline: Add IPV6_ socket options from RFCs 3493 and 3542. + + -- Matthias Klose Fri, 2 Jan 2004 14:03:26 +0100 + +python2.3 (2.3.3-1) unstable; urgency=low + + * New upstream release. + * Copy the templates, tools and scripts from the Doc dir in the source + to /usr/share/lib/python2.3/doc in the python2.3-dev package. Needed + for packages building documentation like python does (closes: #207337). + + -- Matthias Klose Fri, 19 Dec 2003 10:57:39 +0100 + +python2.3 (2.3.2.91-1) unstable; urgency=low + + * New upstream version (2.3.3 release candidate). + * Update python-mode.el (closes: #158811, #159630). + Closing unreproducible report (closes: #159628). + + -- Matthias Klose Sat, 6 Dec 2003 14:41:14 +0100 + +python2.3 (2.3.2-7) unstable; urgency=low + + * Put the conflict in the correct direction. python2.3 (2.3.2-6) doesn't + conflict with python (<= 2.3.2-5) but python (2.3.2-6) conflicts with + python2.3 (<= 2.3.2-5) (thanks to Brian May). Really closes #221791. + + -- Matthias Klose Fri, 21 Nov 2003 00:20:02 +0100 + +python2.3 (2.3.2-6) unstable; urgency=low + + * Add conflicts with older python{,2.3} packages to fix overwrite + errors (closes: #221791). + + -- Matthias Klose Thu, 20 Nov 2003 07:24:36 +0100 + +python2.3 (2.3.2-5) unstable; urgency=low + + * Updated to CVS release23-maint 20031119. + * Re-upgrade the dependency of python2.3 on python (>= 2.3) to + a dependency (closes: #221523). + + -- Matthias Klose Wed, 19 Nov 2003 00:30:27 +0100 + +python2.3 (2.3.2-4) unstable; urgency=low + + * Don't build-depend on latex2html (moved to non-free), but keep + the prebuilt docs in debian/patches (closes: #221347). + * Fix typos in the library reference (closes: #220510, #220954). + * Fix typo in python-elisp's autoloading code (closes: #220308). + * Update proposed python policy: private modules can be installed + into /usr/lib/ (arch dependent) and into /usr/share/ + (arch independent). + + -- Matthias Klose Tue, 18 Nov 2003 00:41:39 +0100 + +python2.3 (2.3.2-3) unstable; urgency=low + + * Downgrade the dependency of python2.3 on python (>= 2.3) to + a recommendation. + * Fix path to interpreter in binfmt file. + * Fix segfault in unicodedata module (closes: #218697). + * Adjust python-elisp autoload code (closes: #219821). + + -- Matthias Klose Sun, 9 Nov 2003 19:43:37 +0100 + +python2.3 (2.3.2-2) unstable; urgency=medium + + * Fix broken doc link (closes: #214217). + * Disable wrongly detected large file support for GNU/Hurd. + * Really fix the FTBFS for the binary-indep target (closes: #214303). + + -- Matthias Klose Mon, 6 Oct 2003 07:54:58 +0200 + +python2.3 (2.3.2-1) unstable; urgency=low + + * New upstream version. + * Fix a FTBFS for the binary-indep target. + + -- Matthias Klose Sat, 4 Oct 2003 10:20:15 +0200 + +python2.3 (2.3.1-3) unstable; urgency=low + + * Fix names of codec packages in recommends. + * On alpha compile using -mieee (see #212912). + + -- Matthias Klose Sun, 28 Sep 2003 10:48:12 +0200 + +python2.3 (2.3.1-2) unstable; urgency=low + + * Update python policy draft (closes: #128911, #163785). + * Re-add os.fsync function (closes: #212672). + * Let python2.3-doc conflict with older python2.3 versions (closes: #211882). + * Add recommends for pythonX.Y-japanese-codecs, pythonX.Y-iconvcodec, + pythonX.Y-cjkcodecs, pythonX.Y-korean-codecs (closes: #207161). + * Generate binfmt file (closes: #208005). + * Add IPPROTO_IPV6 option to the socketmodule (closes: #206569). + * Bugs reported against python2.2 and fixed in python2.3: + - Crashes in idle (closes: #186887, #200084). + + -- Matthias Klose Sat, 27 Sep 2003 11:21:47 +0200 + +python2.3 (2.3.1-1) unstable; urgency=low + + * New upstream version (bug fix release). + + -- Matthias Klose Wed, 24 Sep 2003 11:27:43 +0200 + +python2.3 (2.3-4) unstable; urgency=high + + * Disable check for utimes function, which is broken in glibc-2.3.2. + Packages using distutils had '1970/01/01-01:00:01' timestamps in files. + * Bugs fixed by making python2.3 the default python version: + - Canvas.scan_dragto() takes a 3rd optional parmeter "gain". + Closes: #158168. + - New command line parsing module (closes: #38628). + - compileall.py allows compiling single files (closes: #139971). + * Bugs reported for 2.2 and fixed in 2.3: + - Idle does save files with ASCII characters (closes: #179313). + - imaplib support for prefix-quoted strings (closes: #150485). + - posixpath includes getctime (closes: #173827). + - pydoc has support for keywords (closes: #186775). + * Bugs reported for 2.1 and fixed in 2.3: + - Fix handling of "#anchor" URLs in urlparse (closes: #147844). + - Fix readline if C stdin is not a tty, even if sys.stdin is. + Closes: #131810. + * Updated to CVS release23-maint 20030810 (fixing memory leaks in + array and socket modules). + * pydoc's usage output uses the basename of the script. + * Don't explicitely remove /etc/python2.3 on purge (closes: #202864). + * python conflicts with python-xmlbase (closes: #204773). + * Add dependency python (>= 2.3) to python2.3, so make sure the + unversioned names can be used. + + -- Matthias Klose Sun, 10 Aug 2003 09:27:52 +0200 + +python2.3 (2.3-3) unstable; urgency=medium + + * Fix shlibs file. + + -- Matthias Klose Fri, 8 Aug 2003 08:45:12 +0200 + +python2.3 (2.3-2) unstable; urgency=medium + + * Make python2.3 the default python version. + + -- Matthias Klose Tue, 5 Aug 2003 22:13:22 +0200 + +python2.3 (2.3-1) unstable; urgency=low + + * Python 2.3 final release. + + -- Matthias Klose Wed, 30 Jul 2003 08:12:28 +0200 + +python2.3 (2.2.107-1rc2) unstable; urgency=medium + + * Python 2.3 release candidate 2. + * Don't compress .txt files referenced by the html docs (closes: #200298). + * Include the email/_compat* files (closes: #200349). + + -- Matthias Klose Fri, 25 Jul 2003 07:08:09 +0200 + +python2.3 (2.2.106-2beta2) unstable; urgency=medium + + * Python 2.3 beta2 release, updated to CVS 20030704. + - Fixes AssertionError in httplib (closed: #192452). + - Fixes uncaught division by zero in difflib.py (closed: #199287). + * Detect presence of setgroups(2) at configure time (closes: #199839). + * Use default gcc on arm as well. + + -- Matthias Klose Sat, 5 Jul 2003 10:21:33 +0200 + +python2.3 (2.2.105-1beta2) unstable; urgency=low + + * Python 2.3 beta2 release. + - Includes merged idle fork. + - Fixed socket.setdefaulttimeout(). Closes: #189380. + - socket.ssl works with _socketobj. Closes: #196082. + * Do not link libtix to the _tkinter module. It's loaded via + 'package require tix' at runtime. python2.3-tkinter now + suggests tix8.1 instead. + * On arm, use gcc-3.2 to build. + * Add -fno-strict-aliasing rules to OPT to avoid warnings + "dereferencing type-punned pointer will break strict-aliasing rules", + when building with gcc-3.3. + + -- Matthias Klose Mon, 30 Jun 2003 00:19:32 +0200 + +python2.3 (2.2.104-1beta1.1) unstable; urgency=low + + * Non-maintainer upload with maintainer consent. + * debian/control (Build-Depends): s/libgdbmg1-dev/libgdbm-dev/. + + -- James Troup Wed, 4 Jun 2003 02:24:27 +0100 + +python2.3 (2.2.104-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030514. + - build the current documentation. + * Reenable Tix support. + + -- Matthias Klose Wed, 14 May 2003 07:38:57 +0200 + +python2.3 (2.2.103-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030506. + - updated due to build problems on mips/mipsel. + - keep the 2.3b1 documentation (doc build problems with cvs). + + -- Matthias Klose Wed, 7 May 2003 06:26:39 +0200 + +python2.3 (2.2.102-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release. + + -- Matthias Klose Sat, 3 May 2003 22:45:16 +0200 + +python2.3 (2.2.101-1exp1) unstable; urgency=medium + + * Python 2.3 alpha2 release, updated to CVS 20030321. + * Tkinter: Catch exceptions thrown for undefined substitutions in + events (needed for tk 8.4.2). + + -- Matthias Klose Fri, 21 Mar 2003 21:32:14 +0100 + +python2.3 (2.2.100-1exp1) unstable; urgency=low + + * Python 2.3 alpha2 release, updated to CVS 20030221. + + -- Matthias Klose Fri, 21 Feb 2003 19:37:17 +0100 + +python2.3 (2.2.99-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030123. + - should fix the testsuite (and package build) failure on alpha. + * Remove build dependency on libexpat1-dev. Merge the python2.3-xmlbase + package into python2.3 (closes: #177739). + + -- Matthias Klose Thu, 23 Jan 2003 22:48:12 +0100 + +python2.3 (2.2.98-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030117. + * Build using libdb4.1. + + -- Matthias Klose Sat, 18 Jan 2003 00:14:01 +0100 + +python2.3 (2.2.97-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030109. + * Build-Depend on g++ (>= 3:3.2). + * Python package maintainers: please wait uploading python dependent + packages until python2.2 and python2.1 are compiled using gcc-3.2. + + -- Matthias Klose Thu, 9 Jan 2003 23:56:42 +0100 + +python2.3 (2.2.96-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release (not exactly the tarball, but taken from + CVS 20030101). + - Includes support for linking with threaded tk8.4 (closes: #172714). + * Install and register whatsnew document (closes: #173859). + * Properly unregister info documentation. + + -- Matthias Klose Wed, 1 Jan 2003 17:38:54 +0100 + +python2.3 (2.2.95-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021212. + - data in unicodedate module is up to date (closes: #171061). + * Fix idle packaging (closes: #170394). + * Configure using unicode UCS-4 (closes: #171062). + This change breaks compatibility with binary modules, but what do you + expect from experimental packages ... Please recompile dependent packages. + * Don't strip binaries for now. + + -- Matthias Klose Thu, 12 Dec 2002 21:42:27 +0100 + +python2.3 (2.2.94-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021120. + * Remove outdated README.dbm. + * Depend on tk8.4. + * python-elisp: Install emacsen install file with mode 644 (closes: #167718). + + -- Matthias Klose Thu, 21 Nov 2002 01:04:51 +0100 + +python2.3 (2.2.93-1exp1) unstable; urgency=medium + + * Experimental packages from CVS 021015. + * Build a static library libpython2.3-pic.a. + * Enable large file support for the Hurd (closes: #164602). + + -- Matthias Klose Tue, 15 Oct 2002 21:06:27 +0200 + +python2.3 (2.2.92-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020922. + * Fix build error on ia64 (closes: #161234). + * Build depend on gcc-3.2-3.2.1-0pre2 to fix build error on arm. + + -- Matthias Klose Sun, 22 Sep 2002 18:30:28 +0200 + +python2.3 (2.2.91-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020906. + * idle-python2.3: Fix conflict (closes: #159267). + * Fix location of python-mode.el (closes: #159564, #159619). + * Use tix8.1. + * Apply fix for distutils/ccompiler problem (closes: #159288). + + -- Matthias Klose Sat, 7 Sep 2002 09:55:07 +0200 + +python2.3 (2.2.90-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020820. + * Don't build python2.3-elisp, but put the latest version into + python-elisp. + + -- Matthias Klose Thu, 22 Aug 2002 21:52:04 +0200 + +python2.2 (2.2.1-6) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-07-23. + * Enable IPv6 support (closes: #152543). + * Add python2.2-tk suggestion for python2.2 (pydoc -g). + * Fix from SF patch #527518: proxy config with user+pass authentication. + * Point pydoc to the correct location of the docs (closes: #147579). + * Remove '*.py[co]' files, when removing the python package, + not when purging (closes: #147130). + * Update to new py2texi.el version (Milan Zamazal). + + -- Matthias Klose Mon, 29 Jul 2002 23:11:32 +0200 + +python2.2 (2.2.1-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-05-03. + * Build the info docs (closes: #145653). + + -- Matthias Klose Fri, 3 May 2002 22:35:46 +0200 + +python2.2 (2.2.1-4) unstable; urgency=high + + * Fix indentation errors introduced in last upload (closes: #143809). + + -- Matthias Klose Sun, 21 Apr 2002 01:00:14 +0200 + +python2.2 (2.2.1-3) unstable; urgency=high + + * Add Build-Conflicts: tcl8.0-dev, tk8.0-dev, tcl8.2-dev, tk8.2-dev. + Closes: #143534 (build a working _tkinter module, on machines, where + 8.0's tk.h gets included). + * CVS updates of the release22-maint branch upto 2002-04-20. + + -- Matthias Klose Sat, 20 Apr 2002 09:22:37 +0200 + +python2.2 (2.2.1-2) unstable; urgency=low + + * Forgot to copy the dlmodule patch from the 2.1.3 package. Really + closes: #141681. + + -- Matthias Klose Sat, 13 Apr 2002 01:28:05 +0200 + +python2.2 (2.2.1-1) unstable; urgency=high + + * Final 2.2.1 release. + * According to report #131813, the python interpreter is much faster on some + architectures, when beeing linked statically with the python library (25%). + Gregor and me tested on i386, m68k and alpha, but we could not reproduce + such a speedup (generally between 5% and 10%). But we are linking the + python executable now statically ... + * Build info docs from the tex source, merge the python-doc-info + package into the python-doc package. + * Always build the dl module. Failure in case of + sizeof(int)!=sizeof(long)!=sizeof(void*) + is delayed until dl.open is called. Closes: #141681. + + -- Matthias Klose Thu, 11 Apr 2002 00:19:19 +0200 + +python2.2 (2.2.0.92-0) unstable; urgency=low + + * Package CVS sources, omit cvs-updates.dpatch (closes: #140977). + + -- Matthias Klose Wed, 3 Apr 2002 08:20:52 +0200 + +python2.2 (2.2-6) unstable; urgency=medium + + * Update to python-2.2.1 release candidate 2 (final release scheduled + for April 10). + * Enable dl module (closes: #138992). + * Build doc files with python binary from package (closes: #139657). + * Build _tkinter module with BLT and Tix support. + * python2.2-elisp: Conflict with python2-elisp (closes: #138970). + * string.split docs updated in python-2.2.1 (closes: #129272). + + -- Matthias Klose Mon, 1 Apr 2002 13:52:36 +0200 + +python2.2 (2.2-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 20020310 (aproaching + the first 2.2.1 release candidate). + * Stolen from HEAD: check argument of locale.nl_langinfo (closes: #137371). + + -- Matthias Klose Fri, 15 Mar 2002 01:05:59 +0100 + +python2.2 (2.2-4) unstable; urgency=medium + + * Include test/{__init__.py,README,pystone.py} in package (closes: #129013). + * Fix python-elisp conflict (closes: #129046). + * Don't compress stylesheets (closes: #133179). + * CVS updates of the release22-maint branch upto 20020310. + + -- Matthias Klose Sun, 10 Mar 2002 23:32:28 +0100 + +python2.2 (2.2-3) unstable; urgency=medium + + * Updates from the CVS python22-maint branch up to 20020107. + webbrowser.py: properly escape url's. + * The Hurd does not have large file support: disabled. + + -- Matthias Klose Mon, 7 Jan 2002 21:55:57 +0100 + +python2.2 (2.2-2) unstable; urgency=medium + + * CVS updates of the release22-maint branch upto 20011229. Fixes: + - Include TCP_CORK flag in plat-linux2 headers (fixes: #84340). + - Update CDROM.py module (fixes: #125785). + * Add missing chunk of the GNU/Hurd patch (therefore urgency medium). + * Send anonymous password when using anonftp (closes: #126814). + + -- Matthias Klose Sat, 29 Dec 2001 20:18:26 +0100 + +python2.2 (2.2-1) unstable; urgency=low + + * New upstream version: 2.2. + * Bugs fixed upstream: + - Docs for os.kill reference the signal module for constants. + - Documentation strings in the tutorial end with a period (closes: #94770). + - Tk: grid_location method moved from Grid to Misc (closes: #98338). + - mhlib.SubMessage.getbodytext takes decode parameter (closes: #31876). + - Strings in modules are locale aware (closes: #51444). + - Printable 8-bit characters in strings are correctly printed + (closes: #64354). + - Dictionary can be updated with abstract mapping object (closes: #46566). + * Make site.py a config files. + + -- Matthias Klose Sat, 22 Dec 2001 00:51:46 +0100 + +python2.2 (2.1.99c1-1) unstable; urgency=low + + * New upstream version: 2.2c1 (release candidate). + * Do not provide python2.2-base anymore. + * Install correct README.Debian for python2.2 package. Include hint + where to find Makefile.pre.in. + * Suggest installation of python-ssl. + * Remove idle config files on purge. + * Remove empty /usr/lib/python2.2 directory on purge. + + -- Matthias Klose Sat, 15 Dec 2001 17:56:27 +0100 + +python2.2 (2.1.99beta2-1) unstable; urgency=high + + * debian/rules: Reflect removal of regrtest package (closes: #122278). + Resulted in build failures on all architectures. + * Build -doc package from source. + + -- Matthias Klose Sat, 8 Dec 2001 00:38:41 +0100 + +python2.2 (2.1.99beta2-0.1) unstable; urgency=low + + * Non maintainer upload. + * New upstream version (this is 2.2beta2). + * Do not build the python-regrtest package anymore; keep the test framework + components test/regrtest.py and test/test_support.py in the python + package (closes: #119408). + + -- Gregor Hoffleit Tue, 27 Nov 2001 09:53:26 +0100 + +python2.2 (2.1.99beta1-4) unstable; urgency=low + + * Configure with --with-fpectl (closes: #118125). + * setup.py: Remove broken check for _curses_panel module (#116081). + * idle: Move config-* files to /etc and mark as conffiles (#106390). + * Move idle packages to section `devel'. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-3) unstable; urgency=low + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * README.Debian: point to draft of python-policy in the python package. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-2) unstable; urgency=medium + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * Rename package python2.2-base to python2.2. + + -- Matthias Klose Wed, 24 Oct 2001 23:00:50 +0200 + +python2.2 (2.1.99beta1-1) unstable; urgency=low + + * New upstream version (beta). Call the package version 2.1.99beta1-1. + * New maintainer until the final 2.2 release. + * Updated the debian patches. + + -- Matthias Klose Sat, 20 Oct 2001 18:56:26 +0200 + +python2.1 (2.1.1-1.2) unstable; urgency=low + + * Really remove the python alternative. + + -- Matthias Klose Sat, 20 Oct 2001 15:16:56 +0200 + +python2.1 (2.1.1-1.1) unstable; urgency=low + + * README FOR PACKAGE MAINTAINERS: It is planned to remove the python2-XXX + packages from unstable and move on to python2.1. + If you repackage/adapt your modules for python2.1, don't build + python2-XXX and python2.1-XXX packages from the same source package, + so that the python2-XXX package can be removed without influencing the + python2.1-XXX package. + + See the debian-python mailing list at http://lists.debian.org/devel.html + for details and the current discussion and a draft for a debian-python + policy (August to October 2001). + + * Remove alternative for /usr/bin/python. The python-base package now + provides the default python version. + + * Regenerate control file to fix build dependencies (closes: #116190). + * Remove alternative for /usr/bin/{python,pydoc}. + * Provide a libpython2.1.so symlink in /usr/lib/python2.1/config, + so that the shared library is found when -L/usr/lib/python2.1/config + is specified. + * Conflict with old package versions, where /usr/bin/python is a real + program (closes: #115943). + * python2.1-elisp conflicts with python-elisp (closes: #115895). + * We now have 2.1 (closes: #96851, #107849, #110243). + + -- Matthias Klose Fri, 19 Oct 2001 17:34:41 +0200 + +python2.1 (2.1.1-1) unstable; urgency=low + + * Incorporated Matthias' modifications. + + -- Gregor Hoffleit Thu, 11 Oct 2001 00:16:42 +0200 + +python2.1 (2.1.1-0.2) unstable; urgency=low + + * New upstream 2.1.1. + * GPL compatible licence (fixes #84080, #102949, #110643). + * Fixed upstream (closes: #99692, #111340). + * Build in separate build directory. + * Split Debian patches into debian/patches directory. + * Build dependencies: Add libgmp3-dev, libexpat1-dev, tighten + debhelper dependency. + * debian/rules: Updated a "bit". + * python-elisp: Remove custom dependency (closes: #87783), + fix emacs path (closes: #89712), remove emacs19 dependency (#82694). + * Mention distutils in python-dev package description (closes: #108170). + * Update README.Debian (closes: #85430). + * Run versioned python in postinsts (closes: #113349). + * debian/sample.{postinst,prerm}: Change to version independent scripts. + * Use '/usr/bin/env python2.1' as interpreter for all python scripts. + * Add libssl-dev to Build-Conflicts. + * python-elisp: Add support for emacs21 (closes: #98635). + * Do not compress .py files in doc directories. + * Don't link explicitely with libc. + + -- Matthias Klose Wed, 3 Oct 2001 09:53:08 +0200 + +python2.1 (2.1.1-0.1) unstable; urgency=low + + * New upstream version (CVS branch release21-maint, will become 2.1.1): + This CVS branch will be released as 2.1.1 under a GPL compatible + license. + + -- Gregor Hoffleit Wed, 27 Jun 2001 22:47:58 +0200 + +python2 (2.1-0.1) unstable; urgency=low + + * Fixed Makefile.pre.in. + * Fixed the postinst files in order to use 2.1 (instead of 2.0). + * Mention the immanent release of 2.0.1 and 2.1.1, with a GPL + compatible license. + + -- Gregor Hoffleit Sun, 17 Jun 2001 21:05:25 +0200 + +python2 (2.1-0) unstable; urgency=low + + * New upstream version. + * Experimental packages. + + -- Gregor Hoffleit Thu, 10 May 2001 00:20:04 +0200 + +python2 (2.0-7) unstable; urgency=low + + * Rebuilt with recent tcl8.3-dev/tk8.3-dev in order to fix a + dependency problem with python2-tk (closes: #87793, #92962). + * Change postinst to create and update /usr/local/lib/python2.0 and + site-python with permissions and owner as mandated by policy: + 2775 and root:staff (closes: #89047). + * Fix to compileall.py: A superfluous argument made compileall without + options fail (cf. #92990 for python). + * Move the distutils module into python2-dev. It needs Makefile.pre.in + in order to work (closes: #89900). + * Remove build-dependency on libgdbm2-dev (which isn't built anyway). + * Add a build-dependency on libdb2-dev (cf. #90220 for python). + + -- Gregor Hoffleit Sat, 14 Apr 2001 21:07:51 +0200 + +python2 (2.0-6) unstable; urgency=low + + * Remove python-zlib package; merge it into python-base. + * Mark that README.python2 is not yet updated. + + -- Gregor Hoffleit Wed, 21 Feb 2001 12:34:18 +0100 + +python2 (2.0-5) unstable; urgency=low + + * Recompile with tcl/tk8.3 (closes: #82088). + * Modifications to README.why-python2 (closes: #82116). + * Add menu hint to idle2 menu entry. + * idle2 is renamed idle-python2 and now build correctly (closes: #82218). + * Add build-dependency on autoconf (closes: #85339). + * Build bsddbmodule as shared module (Modules/Setup.config.in), + and link libpython2.so with -lm in Makefile (closes: #86027). + * various cleanups in debian/rules, e.g. removing dh_suidregister. + * Make pdb available as /usr/bin/pdb-python2 in python2-dev + (cf. #79870 in python-base). + * Remove libgmp3 from build-dependencies, since we currently can't + build the mpzmodule for Python2 due to license problems. + + -- Gregor Hoffleit Sun, 18 Feb 2001 00:12:17 +0100 + +python2 (2.0-4) unstable; urgency=low + + * control: make python2-elisp conflict with python-elisp (it doesn't + make sense to have both of them installed, does it ?) + * include build-depend on libxmltok1-dev. + * again, build with tcl/tk8.0. + + -- Gregor Hoffleit Wed, 10 Jan 2001 23:37:01 +0100 + +python2 (2.0-3) unstable; urgency=low + + * Modules/Setup.in: Added a missing \ that made _tkinter be built + incorrectly. + * rules: on the fly, change all '#!' python scripts to use python2. + + -- Gregor Hoffleit Wed, 13 Dec 2000 20:07:24 +0100 + +python2 (2.0-2) unstable; urgency=low + + * Aaargh. Remove conflicts/provides/replaces on python-base to make + parallel installation of python-base and python2-base possible. + * Install examples into /usr/share/doc/python2 (not python) and fix + symlink to python2.0 (thanks to Rick Younie for + pointing out this). + * Rename man page to python2.1. + + -- Gregor Hoffleit Wed, 13 Dec 2000 09:31:05 +0100 + +python2 (2.0-1) unstable; urgency=low + + * New upstream version. Initial release for python2. + + -- Gregor Hoffleit Mon, 11 Dec 2000 22:39:46 +0100 --- python2.7-2.7.15.orig/debian/changelog.shared +++ python2.7-2.7.15/debian/changelog.shared @@ -0,0 +1,3 @@ + * Link the interpreter against the shared runtime library. With + gcc-4.1 the difference in the pystones benchmark dropped from about + 12% to about 5%. --- python2.7-2.7.15.orig/debian/compat +++ python2.7-2.7.15/debian/compat @@ -0,0 +1 @@ +9 --- python2.7-2.7.15.orig/debian/control +++ python2.7-2.7.15/debian/control @@ -0,0 +1,218 @@ +Source: python2.7 +Section: python +Priority: optional +Maintainer: Ubuntu Core Developers +XSBC-Original-Maintainer: Matthias Klose +Build-Depends: debhelper (>= 9), dpkg-dev (>= 1.17.11), + quilt, autoconf, autotools-dev, + lsb-release, sharutils, + libreadline-dev, libtinfo-dev, libncursesw5-dev (>= 5.3), + tk-dev, blt-dev (>= 2.4z), libssl-dev, + zlib1g-dev, libbz2-dev, + libexpat1-dev, + libbluetooth-dev [linux-any] , + locales [!armel !avr32 !hppa !ia64 !mipsel], + libsqlite3-dev, libffi-dev (>= 3.0.5) [!or1k !avr32], + libgpm2 [linux-any], + mime-support, netbase, net-tools, bzip2, time, + libdb-dev (<< 1:6.0), libgdbm-dev, python:any, help2man, + xvfb, xauth +Build-Depends-Indep: python3-sphinx +Build-Conflicts: tcl8.4-dev, tk8.4-dev, + python2.7-xml, python-xml, + autoconf2.13, python-cxx-dev, + hardening-wrapper +Standards-Version: 4.2.1 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg2.7-debian +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg2.7-debian +XS-Testsuite: autopkgtest + +Package: python2.7 +Architecture: any +Multi-Arch: allowed +Priority: optional +Depends: python2.7-minimal (= ${binary:Version}), libpython2.7-stdlib (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Suggests: python2.7-doc, binutils +Conflicts: python-profiler (<= 2.7.1-2) +Breaks: python-virtualenv (<< 1.7.1.2-2~), vim-nox (<< 2:7.3.547-4), vim-gtk (<< 2:7.3.547-4), vim-gnome (<< 2:7.3.547-4), vim-athena (<< 2:7.3.547-4) +Replaces: python-profiler (<= 2.7.1-2), python2.7-minimal (<< 2.7.3-7~) +Description: Interactive high-level object-oriented language (version 2.7) + Python is a high-level, interactive, object-oriented language. Its 2.7 version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + +Package: libpython2.7-stdlib +Architecture: any +Multi-Arch: same +Priority: optional +Depends: libpython2.7-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Provides: python2.7-cjkcodecs, python2.7-ctypes, python2.7-elementtree, python2.7-celementtree, python2.7-wsgiref, python2.7-profiler, python2.7-argparse, python-argparse +Replaces: python2.7 (<< 2.7.5-0~), libpython2.7-testsuite (<< 2.7.13-4) +Breaks: python-urllib3 (<< 1.9.1-3), ${pyfpe:Breaks} +Description: Interactive high-level object-oriented language (standard library, version 2.7) + Python is a high-level, interactive, object-oriented language. Its 2.7 version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains Python 2.7's standard library. It is normally not + used on its own, but as a dependency of python2.7. + +Package: python2.7-minimal +Architecture: any +Multi-Arch: allowed +Priority: optional +Pre-Depends: ${shlibs:Pre-Depends} +Depends: libpython2.7-minimal (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Recommends: python2.7 +Suggests: binfmt-support +Replaces: python2.7 (<< 2.7.8-7~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version 2.7) + This package contains the interpreter and some essential modules. It can + be used in the boot process for some basic tasks. + See /usr/share/doc/python2.7-minimal/README.Debian for a list of the modules + contained in this package. + +Package: libpython2.7-minimal +Architecture: any +Multi-Arch: same +Priority: optional +Depends: ${shlibs:Depends}, ${misc:Depends} +Recommends: libpython2.7-stdlib +Replaces: python2.7 (<< 2.7.4-2), python2.7-minimal (<< 2.7.3-10), libpython2.7-stdlib (<< 2.7.8-7) +Breaks: python2.7-minimal (<< 2.7.4~rc1-1~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version 2.7) + This package contains some essential modules. It is normally not + used on it's own, but as a dependency of python2.7-minimal. + +Package: libpython2.7 +Architecture: any +Multi-Arch: same +Section: libs +Priority: optional +Pre-Depends: ${misc:Pre-Depends} +Depends: libpython2.7-stdlib (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: python2.7 (<< 2.6) +Description: Shared Python runtime library (version 2.7) + Python is a high-level, interactive, object-oriented language. Its 2.7 version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains the shared runtime library, normally not needed + for programs using the statically linked interpreter. + +Package: python2.7-examples +Architecture: all +Multi-Arch: foreign +Depends: python2.7:any (>= ${source:Version}), ${misc:Depends} +Description: Examples for the Python language (v2.7) + Examples, Demos and Tools for Python (v2.7). These are files included in + the upstream Python distribution (v2.7). + +Package: python2.7-dev +Architecture: any +Multi-Arch: allowed +Depends: python2.7 (= ${binary:Version}), libpython2.7-dev (= ${binary:Version}), libpython2.7 (= ${binary:Version}), libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Recommends: libc6-dev | libc-dev +Replaces: python2.7 (<< 2.7-3) +Description: Header files and a static library for Python (v2.7) + Header files, a static library and development tools for building + Python (v2.7) modules, extending the Python interpreter or embedding + Python (v2.7) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: libpython2.7-dev +Section: libdevel +Architecture: any +Multi-Arch: same +Pre-Depends: ${misc:Pre-Depends} +Depends: libpython2.7-stdlib (= ${binary:Version}), libpython2.7 (= ${binary:Version}), libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Replaces: python2.7 (<< 2.7-3), python2.7-dev (<< 2.7.3-10), python2.7-minimal (<< 2.7.3-10) +Recommends: libc6-dev | libc-dev +Description: Header files and a static library for Python (v2.7) + Header files, a static library and development tools for building + Python (v2.7) modules, extending the Python interpreter or embedding + Python (v2.7) in applications. + . + Maintainers of Python packages should read README.maintainers. + . + This package contains development files. It is normally not + used on it's own, but as a dependency of python2.7-dev. + +Package: libpython2.7-testsuite +Section: libdevel +Architecture: all +Depends: libpython2.7-stdlib (>= ${binary:Version}), ${misc:Depends} +Suggests: python-gdbm, python-tk +Description: Testsuite for the Python standard library (v2.7) + The complete testsuite for the Python standard library. Note that + a subset is found in the libpython2.7-stdlib package, which should + be enough for other packages to use (please do not build-depend + on this package, but file a bug report to include additional + testsuite files in the libpython2.7-stdlib package). + +Package: idle-python2.7 +Architecture: all +Depends: python2.7, python-tk (>= 2.6~a3), python2.7-tk, ${misc:Depends} +Enhances: python2.7 +Replaces: python2.7 (<< 2.6.1-2) +Description: IDE for Python (v2.7) using Tkinter + IDLE is an Integrated Development Environment for Python (v2.7). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: python2.7-doc +Section: doc +Architecture: all +Multi-Arch: foreign +Depends: libjs-jquery, libjs-underscore, ${misc:Depends} +Suggests: python2.7 +Description: Documentation for the high-level object-oriented language Python (v2.7) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v2.7). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python2.7 + * Tutorial + * Python Library Reference + * Macintosh Module Reference + * Python Language Reference + * Extending and Embedding Python + * Python/C API Reference + * Installing Python Modules + * Documenting Python + * Distributing Python Modules + +Package: python2.7-dbg +Section: debug +Architecture: any +Multi-Arch: allowed +Depends: python2.7 (= ${binary:Version}), libpython2.7-dbg (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: python-gdbm-dbg, python-tk-dbg +Description: Debug Build of the Python Interpreter (version 2.7) + The package holds two things: + . + - A Python interpreter configured with --pydebug. Dynamically loaded modules + are searched as _d.so first. Third party extensions need a separate + build to be used by this interpreter. + - Debug information for standard python interpreter and extensions. + . + See the README.debug for more information. + +Package: libpython2.7-dbg +Section: debug +Architecture: any +Multi-Arch: same +Pre-Depends: ${misc:Pre-Depends} +Depends: libpython2.7-stdlib (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: python2.7-gdbm-dbg, python2.7-tk-dbg +Replaces: python2.7-dbg (<< 2.7.3-10) +Description: Debug Build of the Python Interpreter (version 2.7) + The package holds two things: + . + - Extensions for a Python interpreter configured with --pydebug. + - Debug information for standard python extensions. + . + See the README.debug for more information. + --- python2.7-2.7.15.orig/debian/control.in +++ python2.7-2.7.15/debian/control.in @@ -0,0 +1,217 @@ +Source: @PVER@ +Section: python +Priority: optional +Maintainer: Matthias Klose +Build-Depends: debhelper (>= 9), @bd_dpkgdev@ @bd_gcc@ + quilt, autoconf, autotools-dev, + lsb-release, sharutils, + libreadline-dev, libtinfo-dev, libncursesw5-dev (>= 5.3), + tk-dev, blt-dev (>= 2.4z), libssl-dev, + zlib1g-dev, libbz2-dev, + libexpat1-dev, + libbluetooth-dev [linux-any]@pf_bluetooth@, + locales [!armel !avr32 !hppa !ia64 !mipsel], + libsqlite3-dev, libffi-dev (>= 3.0.5) [!or1k !avr32], + libgpm2 [linux-any], + mime-support, netbase, net-tools, bzip2, time, + libdb-dev (<< 1:6.0), libgdbm-dev, python@bd_qual@, help2man, + xvfb, xauth +Build-Depends-Indep: python3-sphinx +Build-Conflicts: tcl8.4-dev, tk8.4-dev, + @PVER@-xml, python-xml, + autoconf2.13, python-cxx-dev, + hardening-wrapper +Standards-Version: 4.2.1 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg@VER@-debian +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg@VER@-debian +XS-Testsuite: autopkgtest + +Package: @PVER@ +Architecture: any +Multi-Arch: allowed +Priority: @PRIO@ +Depends: @PVER@-minimal (= ${binary:Version}), lib@PVER@-stdlib (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Suggests: @PVER@-doc, binutils +Conflicts: python-profiler (<= 2.7.1-2) +Breaks: python-virtualenv (<< 1.7.1.2-2~), vim-nox (<< 2:7.3.547-4), vim-gtk (<< 2:7.3.547-4), vim-gnome (<< 2:7.3.547-4), vim-athena (<< 2:7.3.547-4) +Replaces: python-profiler (<= 2.7.1-2), @PVER@-minimal (<< 2.7.3-7~) +Description: Interactive high-level object-oriented language (version @VER@) + Python is a high-level, interactive, object-oriented language. Its @VER@ version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + +Package: lib@PVER@-stdlib +Architecture: any +Multi-Arch: same +Priority: @PRIO@ +Depends: lib@PVER@-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Provides: @PVER@-cjkcodecs, @PVER@-ctypes, @PVER@-elementtree, @PVER@-celementtree, @PVER@-wsgiref, @PVER@-profiler, @PVER@-argparse, python-argparse +Replaces: @PVER@ (<< 2.7.5-0~), lib@PVER@-testsuite (<< 2.7.13-4) +Breaks: python-urllib3 (<< 1.9.1-3), ${pyfpe:Breaks} +Description: Interactive high-level object-oriented language (standard library, version @VER@) + Python is a high-level, interactive, object-oriented language. Its @VER@ version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains Python @VER@'s standard library. It is normally not + used on its own, but as a dependency of python@VER@. + +Package: @PVER@-minimal +Architecture: any +Multi-Arch: allowed +Priority: @MINPRIO@ +Pre-Depends: ${shlibs:Pre-Depends} +Depends: lib@PVER@-minimal (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Recommends: @PVER@ +Suggests: binfmt-support +Replaces: @PVER@ (<< 2.7.8-7~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version @VER@) + This package contains the interpreter and some essential modules. It can + be used in the boot process for some basic tasks. + See /usr/share/doc/@PVER@-minimal/README.Debian for a list of the modules + contained in this package. + +Package: lib@PVER@-minimal +Architecture: any +Multi-Arch: same +Priority: @MINPRIO@ +Depends: ${shlibs:Depends}, ${misc:Depends} +Recommends: lib@PVER@-stdlib +Replaces: @PVER@ (<< 2.7.4-2), @PVER@-minimal (<< 2.7.3-10), lib@PVER@-stdlib (<< 2.7.8-7) +Breaks: @PVER@-minimal (<< 2.7.4~rc1-1~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version @VER@) + This package contains some essential modules. It is normally not + used on it's own, but as a dependency of @PVER@-minimal. + +Package: lib@PVER@ +Architecture: any +Multi-Arch: same +Section: libs +Priority: @PRIO@ +Pre-Depends: ${misc:Pre-Depends} +Depends: lib@PVER@-stdlib (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: @PVER@ (<< 2.6) +Description: Shared Python runtime library (version @VER@) + Python is a high-level, interactive, object-oriented language. Its @VER@ version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains the shared runtime library, normally not needed + for programs using the statically linked interpreter. + +Package: @PVER@-examples +Architecture: all +Multi-Arch: foreign +Depends: @PVER@:any (>= ${source:Version}), ${misc:Depends} +Description: Examples for the Python language (v@VER@) + Examples, Demos and Tools for Python (v@VER@). These are files included in + the upstream Python distribution (v@VER@). + +Package: @PVER@-dev +Architecture: any +Multi-Arch: allowed +Depends: @PVER@ (= ${binary:Version}), lib@PVER@-dev (= ${binary:Version}), lib@PVER@ (= ${binary:Version}), libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Recommends: libc6-dev | libc-dev +Replaces: @PVER@ (<< 2.7-3) +Description: Header files and a static library for Python (v@VER@) + Header files, a static library and development tools for building + Python (v@VER@) modules, extending the Python interpreter or embedding + Python (v@VER@) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: lib@PVER@-dev +Section: libdevel +Architecture: any +Multi-Arch: same +Pre-Depends: ${misc:Pre-Depends} +Depends: lib@PVER@-stdlib (= ${binary:Version}), lib@PVER@ (= ${binary:Version}), libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Replaces: @PVER@ (<< 2.7-3), @PVER@-dev (<< 2.7.3-10), @PVER@-minimal (<< 2.7.3-10) +Recommends: libc6-dev | libc-dev +Description: Header files and a static library for Python (v@VER@) + Header files, a static library and development tools for building + Python (v@VER@) modules, extending the Python interpreter or embedding + Python (v@VER@) in applications. + . + Maintainers of Python packages should read README.maintainers. + . + This package contains development files. It is normally not + used on it's own, but as a dependency of @PVER@-dev. + +Package: lib@PVER@-testsuite +Section: libdevel +Architecture: all +Depends: lib@PVER@-stdlib (>= ${binary:Version}), ${misc:Depends} +Suggests: python-gdbm, python-tk +Description: Testsuite for the Python standard library (v@VER@) + The complete testsuite for the Python standard library. Note that + a subset is found in the lib@PVER@-stdlib package, which should + be enough for other packages to use (please do not build-depend + on this package, but file a bug report to include additional + testsuite files in the lib@PVER@-stdlib package). + +Package: idle-@PVER@ +Architecture: all +Depends: @PVER@, python-tk (>= 2.6~a3), @PVER@-tk, ${misc:Depends} +Enhances: @PVER@ +Replaces: @PVER@ (<< 2.6.1-2) +Description: IDE for Python (v@VER@) using Tkinter + IDLE is an Integrated Development Environment for Python (v@VER@). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: @PVER@-doc +Section: doc +Architecture: all +Multi-Arch: foreign +Depends: libjs-jquery, libjs-underscore, ${misc:Depends} +Suggests: @PVER@ +Description: Documentation for the high-level object-oriented language Python (v@VER@) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v@VER@). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python@VER@ + * Tutorial + * Python Library Reference + * Macintosh Module Reference + * Python Language Reference + * Extending and Embedding Python + * Python/C API Reference + * Installing Python Modules + * Documenting Python + * Distributing Python Modules + +Package: @PVER@-dbg +Section: debug +Architecture: any +Multi-Arch: allowed +Depends: @PVER@ (= ${binary:Version}), lib@PVER@-dbg (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: python-gdbm-dbg, python-tk-dbg +Description: Debug Build of the Python Interpreter (version @VER@) + The package holds two things: + . + - A Python interpreter configured with --pydebug. Dynamically loaded modules + are searched as _d.so first. Third party extensions need a separate + build to be used by this interpreter. + - Debug information for standard python interpreter and extensions. + . + See the README.debug for more information. + +Package: lib@PVER@-dbg +Section: debug +Architecture: any +Multi-Arch: same +Pre-Depends: ${misc:Pre-Depends} +Depends: lib@PVER@-stdlib (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: @PVER@-gdbm-dbg, @PVER@-tk-dbg +Replaces: @PVER@-dbg (<< 2.7.3-10) +Description: Debug Build of the Python Interpreter (version @VER@) + The package holds two things: + . + - Extensions for a Python interpreter configured with --pydebug. + - Debug information for standard python extensions. + . + See the README.debug for more information. + --- python2.7-2.7.15.orig/debian/control.stdlib +++ python2.7-2.7.15/debian/control.stdlib @@ -0,0 +1,16 @@ +Package: @PVER@-tk +Architecture: any +Depends: @PVER@ (= ${Source-Version}), ${shlibs:Depends} +Suggests: tix +XB-Python-Version: @VER@ +Description: Tkinter - Writing Tk applications with Python (v@VER@) + A module for writing portable GUI applications with Python (v@VER@) using Tk. + Also known as Tkinter. + +Package: @PVER@-gdbm +Architecture: any +Depends: @PVER@ (= ${Source-Version}), ${shlibs:Depends} +Description: GNU dbm database support for Python (v@VER@) + GNU dbm database module for Python. Install this if you want to + create or read GNU dbm database files with Python. + --- python2.7-2.7.15.orig/debian/copyright +++ python2.7-2.7.15/debian/copyright @@ -0,0 +1,958 @@ +This package was put together by Klee Dienes from +sources from ftp.python.org:/pub/python, based on the Debianization by +the previous maintainers Bernd S. Brentrup and +Bruce Perens. Current maintainer is Matthias Klose . + +It was downloaded from http://python.org/ + +Copyright: + +Upstream Author: Guido van Rossum and others. + +License: + +The following text includes the Python license and licenses and +acknowledgements for incorporated software. The licenses can be read +in the HTML and texinfo versions of the documentation as well, after +installing the pythonx.y-doc package. Licenses for files not licensed +under the Python Licenses are found at the end of this file. + + +Python License +============== + +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations (now Zope +Corporation, see http://www.zope.com). In 2001, the Python Software +Foundation (PSF, see http://www.python.org/psf/) was formed, a +non-profit organization created specifically to own Python-related +Intellectual Property. Zope Corporation is a sponsoring member of +the PSF. + +All Python releases are Open Source (see http://www.opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.2 2.1.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2.1 2.2 2002 PSF yes + 2.2.2 2.2.1 2002 PSF yes + 2.2.3 2.2.2 2003 PSF yes + 2.3 2.2.2 2002-2003 PSF yes + 2.3.1 2.3 2002-2003 PSF yes + 2.3.2 2.3.1 2002-2003 PSF yes + 2.3.3 2.3.2 2002-2003 PSF yes + 2.3.4 2.3.3 2004 PSF yes + 2.3.5 2.3.4 2005 PSF yes + 2.4 2.3 2004 PSF yes + 2.4.1 2.4 2005 PSF yes + 2.4.2 2.4.1 2005 PSF yes + 2.4.3 2.4.2 2006 PSF yes + 2.5 2.4 2006 PSF yes + 2.5.1 2.5 2007 PSF yes + 2.5.2 2.5.1 2008 PSF yes + 2.5.3 2.5.2 2008 PSF yes + 2.6 2.5 2008 PSF yes + 2.6.1 2.6 2008 PSF yes + 2.6.2 2.6.1 2009 PSF yes + 2.6.3 2.6.2 2009 PSF yes + 2.6.4 2.6.3 2009 PSF yes + 2.6.5 2.6.4 2010 PSF yes + 2.7 2.6 2010 PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python +alone or in any derivative version, provided, however, that PSF's +License Agreement and PSF's notice of copyright, i.e., "Copyright (c) +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the Internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the Internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Licenses and Acknowledgements for Incorporated Software +======================================================= + +Mersenne Twister +---------------- + +The `_random' module includes code based on a download from +`http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html'. The +following are the verbatim comments from the original code: + + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. + + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + 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. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT + OWNER 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. + + Any feedback is very welcome. + http://www.math.keio.ac.jp/matumoto/emt.html + email: matumoto@math.keio.ac.jp + + +Sockets +------- + +The `socket' module uses the functions, `getaddrinfo', and +`getnameinfo', which are coded in separate source files from the WIDE +Project, `http://www.wide.ad.jp/about/index.html'. + + Copyright (C) 1995, 1996, 1997, and 1998 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 + GAI_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 GAI_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 GAI_ANY THEORY OF LIABILITY, WHETHER + IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN GAI_ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + OF THE POSSIBILITY OF SUCH DAMAGE. + + +Floating point exception control +-------------------------------- + +The source for the `fpectl' module includes the following notice: + + --------------------------------------------------------------------- + / Copyright (c) 1996. \ + | The Regents of the University of California. | + | All rights reserved. | + | | + | Permission to use, copy, modify, and distribute this software for | + | any purpose without fee is hereby granted, provided that this en- | + | tire notice is included in all copies of any software which is or | + | includes a copy or modification of this software and in all | + | copies of the supporting documentation for such software. | + | | + | This work was produced at the University of California, Lawrence | + | Livermore National Laboratory under contract no. W-7405-ENG-48 | + | between the U.S. Department of Energy and The Regents of the | + | University of California for the operation of UC LLNL. | + | | + | DISCLAIMER | + | | + | This software was prepared as an account of work sponsored by an | + | agency of the United States Government. Neither the United States | + | Government nor the University of California nor any of their em- | + | ployees, makes any warranty, express or implied, or assumes any | + | liability or responsibility for the accuracy, completeness, or | + | usefulness of any information, apparatus, product, or process | + | disclosed, or represents that its use would not infringe | + | privately-owned rights. Reference herein to any specific commer- | + | cial products, process, or service by trade name, trademark, | + | manufacturer, or otherwise, does not necessarily constitute or | + | imply its endorsement, recommendation, or favoring by the United | + | States Government or the University of California. The views and | + | opinions of authors expressed herein do not necessarily state or | + | reflect those of the United States Government or the University | + | of California, and shall not be used for advertising or product | + \ endorsement purposes. / + --------------------------------------------------------------------- + + +Cookie management +----------------- + +The `Cookie' module contains the following notice: + + Copyright 2000 by Timothy O'Malley + + All Rights Reserved + + Permission to use, copy, modify, and distribute this software + and its documentation for any purpose and without fee is hereby + granted, provided that the above copyright notice appear in all + copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Timothy O'Malley not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR + ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + + +Execution tracing +----------------- + +The `trace' module contains the following notice: + + portions copyright 2001, Autonomous Zones Industries, Inc., all rights... + err... reserved and offered to the public under the terms of the + Python 2.2 license. + Author: Zooko O'Whielacronx + http://zooko.com/ + mailto:zooko@zooko.com + + Copyright 2000, Mojam Media, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1999, Bioreason, Inc., all rights reserved. + Author: Andrew Dalke + + Copyright 1995-1997, Automatrix, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. + + Permission to use, copy, modify, and distribute this Python software and + its associated documentation for any purpose without fee is hereby + granted, provided that the above copyright notice appears in all copies, + and that both that copyright notice and this permission notice appear in + supporting documentation, and that the name of neither Automatrix, + Bioreason or Mojam Media be used in advertising or publicity pertaining + to distribution of the software without specific, written prior + permission. + + +UUencode and UUdecode functions +------------------------------- + +The `uu' module contains the following notice: + + Copyright 1994 by Lance Ellinghouse + Cathedral City, California Republic, United States of America. + All Rights Reserved + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation, and that the name of Lance Ellinghouse + not be used in advertising or publicity pertaining to distribution + of the software without specific, written prior permission. + LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE + FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + Modified by Jack Jansen, CWI, July 1995: + - Use binascii module to do the actual line-by-line conversion + between ascii and binary. This results in a 1000-fold speedup. The C + version is still 5 times faster, though. + - Arguments more compliant with python standard + + +XML Remote Procedure Calls +-------------------------- + +The `xmlrpclib' module contains the following notice: + + The XML-RPC client interface is + + Copyright (c) 1999-2002 by Secret Labs AB + Copyright (c) 1999-2002 by Fredrik Lundh + + By obtaining, using, and/or copying this software and/or its + associated documentation, you agree that you have read, understood, + and will comply with the following terms and conditions: + + Permission to use, copy, modify, and distribute this software and + its associated documentation for any purpose and without fee is + hereby granted, provided that the above copyright notice appears in + all copies, and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Secret Labs AB or the author not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD + TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- + ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR + BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY + DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + OF THIS SOFTWARE. + +Licenses for Software linked to +=============================== + +Note that the choice of GPL compatibility outlined above doesn't extend +to modules linked to particular libraries, since they change the +effective License of the module binary. + + +GNU Readline +------------ + +The 'readline' module makes use of GNU Readline. + + The GNU Readline Library is free software; you can redistribute it + and/or modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2, or (at + your option) any later version. + + On Debian systems, you can find the complete statement in + /usr/share/doc/readline-common/copyright'. A copy of the GNU General + Public License is available in /usr/share/common-licenses/GPL-2'. + + +OpenSSL +------- + +The '_ssl' module makes use of OpenSSL. + + The OpenSSL toolkit stays under a dual license, i.e. both the + conditions of the OpenSSL License and the original SSLeay license + apply to the toolkit. Actually both licenses are BSD-style Open + Source licenses. Note that both licenses are incompatible with + the GPL. + + On Debian systems, you can find the complete license text in + /usr/share/doc/openssl/copyright'. + + +Files with other licenses than the Python License +------------------------------------------------- + +Files: Lib/profile.py Lib/pstats.py +Copyright: Disney Enterprises, Inc. All Rights Reserved. +License: # Licensed to PSF under a Contributor Agreement + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + either express or implied. See the License for the specific language + overning permissions and limitations under the License. + + On Debian systems, the Apache 2.0 license can be found in + /usr/share/common-licenses/Apache-2.0. + +Files: Modules/zlib/* +Copyright: (C) 1995-2010 Jean-loup Gailly and Mark Adler +License: This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + If you use the zlib library in a product, we would appreciate *not* receiving + lengthy legal documents to sign. The sources are provided for free but without + warranty of any kind. The library has been entirely written by Jean-loup + Gailly and Mark Adler; it does not include third-party code. + +Files: Modules/_ctypes/libffi/* +Copyright: Copyright (C) 1996-2009 Red Hat, Inc and others. +License: Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + Documentation: + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 2, or (at your option) any + later version. A copy of the license is included in the + section entitled ``GNU General Public License''. + +Files: Modules/expat/* +Copyright: Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd + and Clark Cooper + Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers +License: Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Files: Misc/python-mode.el +Copyright: Copyright (C) 1992,1993,1994 Tim Peters +License: This software is provided as-is, without express or implied + warranty. Permission to use, copy, modify, distribute or sell this + software, without fee, for any purpose and by any individual or + organization, is hereby granted, provided that the above copyright + notice and this paragraph appear in all copies. + +Files: PC/_subprocess.c +Copyright: Copyright (c) 2004 by Fredrik Lundh + Copyright (c) 2004 by Secret Labs AB, http://www.pythonware.com + Copyright (c) 2004 by Peter Astrand +License: + * Permission to use, copy, modify, and distribute this software and + * its associated documentation for any purpose and without fee is + * hereby granted, provided that the above copyright notice appears in + * all copies, and that both that copyright notice and this permission + * notice appear in supporting documentation, and that the name of the + * authors not be used in advertising or publicity pertaining to + * distribution of the software without specific, written prior + * permission. + * + * THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Files: PC/winsound.c +Copyright: Copyright (c) 1999 Toby Dickenson +License: * Permission to use this software in any way is granted without + * fee, provided that the copyright notice above appears in all + * copies. This software is provided "as is" without any warranty. + */ + +/* Modified by Guido van Rossum */ +/* Beep added by Mark Hammond */ +/* Win9X Beep and platform identification added by Uncle Timmy */ + +Files: Lib/ensurepip/_bundled/setuptools-*.whl +License: see above, some license as Python. + +Files: Lib/ensurepip/_bundled/pip-*.whl +Copyright: Copyright © 2008-2013 The pip developers: + Alex Grönholm + Alex Morega + Alexandre Conrad + Andrey Bulgakov + Antti Kaihola + Armin Ronacher + Aziz Köksal + Ben Rosser + Brian Rosner + Carl Meyer + Chris McDonough + Christian Oudard + Clay McClure + Cody Soyland + Daniel Holth + Dave Abrahams + David (d1b) + Dmitry Gladkov + Donald Stufft + Francesco + Geoffrey Lehée + Georgi Valkov + Hugo Lopes Tavares + Ian Bicking + Igor Sobreira + Ionel Maries Cristian + Jakub Vysoky + James Cleveland + Jannis Leidel + Jay Graves + John-Scott Atlakson + Jon Parise + Jonas Nockert + Josh Bronson + Kamal Bin Mustafa + Kelsey Hightower + Kenneth Belitzky + Kumar McMillan + Luke Macken + Masklinn + Marc Abramowitz + Marcus Smith + Markus Hametner + Matt Maker + Maxime R. + Miguel Araujo + Nick Stenning + Nowell Strite + Oliver Tonnhofer + Olivier Girardot + Patrick Jenkins + Paul Moore + Paul Nasrat + Paul Oswald + Paul van der Linden + Peter Waller + Phil Whelan + Piet Delport + Przemek Wrzos + Qiangning Hong + Rafael Caricio + Rene Dudfield + Roey Berman + Ronny Pfannschmidt + Rory McCann + Simon Cross + Stavros Korokithakis + Thomas Fenzl + Thomas Johansson + Vinay Sajip + Vitaly Babiy + W Trevor King + Wil Tan + Hsiaoming Yang +License: Expat + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + . + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + . + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/ipaddress.py +Copyright: 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved + 2007 Google Inc. +License: PSF-2 + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/retrying.py +Copyright: (c) 2013-2014, + (c) 2014, Derek Wilson + (c) 2014, Alex Kuang +License: Apache-2 + +License: Apache-2 + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + . + http://www.apache.org/licenses/LICENSE-2.0 + . + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + . + On Debian-based systems the full text of the Apache version 2.0 license + can be found in /usr/share/common-licenses/Apache-2.0. + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/six.py +Copyright: Copyright (c) 2010-2014 Benjamin Peterson +License: Expat + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/cachecontrol +Copyright: 2015 Eric Larson +License: Apache-2.0 + Copyright 2015 Eric Larson + . + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + . + http://www.apache.org/licenses/LICENSE-2.0 + . + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. + . + See the License for the specific language governing permissions and + limitations under the License. + . + On Debian systems, the license is available at + /usr/share/common-licenses/Apache-2.0 + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/colorama +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/distlib +Copyright: Copyright (C) 2012-2013 The Python Software Foundation + Copyright (C) 2012-2013 Vinay Sajip +License: Python + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/html5lib +html5lib is Copyright (c) 2006 The Authors +Authors: + James Graham - james@hoppipolla.co.uk + Anne van Kesteren - annevankesteren@gmail.com + Lachlan Hunt - lachlan.hunt@lachy.id.au + Matt McDonald - kanashii@kanashii.ca + Sam Ruby - rubys@intertwingly.net + Ian Hickson (Google) - ian@hixie.ch + Thomas Broyer - t.broyer@gmail.com + +License: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/lockfile +Copyright: + © 2014–2015 OpenStack Foundation + © 2007–2012 Skip Montanaro + © 2008–2014 Ben Finney +License: Expat + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/packaging +Copyright: Copyright (C) 2014 Donald Stufft + Copyright (C) 2012-2013 Vinay Sajip +License: Apache-2.0 + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/progress +Copyright: Copyright (c) 2012 Giorgos Verigakis +License: ISC + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/requests +Copyright: 2016, Kenneth Reitz +License: Apache + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/requests/packages/urllib3/* +Copyright: 2008-2016, Andrey Petrov +License: Expat + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py +Copyright: 2009, Raymond Hettinger +License: Expat + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py +Copyright: 2011, Python Software Foundation +License: PSF-2 + +Files: Lib/ensurepip/_bundled/pip-*.whl/pip/_vendor/requests/packages/chardet/* +Copyright: 2006-2008, Mark Pilgrim + 2012-2013, Ian Cordasco +License: LGPL-2.1+ --- python2.7-2.7.15.orig/debian/depgraph.py +++ python2.7-2.7.15/debian/depgraph.py @@ -0,0 +1,199 @@ +#! /usr/bin/python + +# Copyright 2004 Toby Dickenson +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject +# to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +import sys, getopt, colorsys, imp, md5 + +class pydepgraphdot: + + def main(self,argv): + opts,args = getopt.getopt(argv,'',['mono']) + self.colored = 1 + for o,v in opts: + if o=='--mono': + self.colored = 0 + self.render() + + def fix(self,s): + # Convert a module name to a syntactically correct node name + return s.replace('.','_') + + def render(self): + p,t = self.get_data() + + # normalise our input data + for k,d in p.items(): + for v in d.keys(): + if not p.has_key(v): + p[v] = {} + + f = self.get_output_file() + + f.write('digraph G {\n') + #f.write('concentrate = true;\n') + #f.write('ordering = out;\n') + f.write('ranksep=1.0;\n') + f.write('node [style=filled,fontname=Helvetica,fontsize=10];\n') + allkd = p.items() + allkd.sort() + for k,d in allkd: + tk = t.get(k) + if self.use(k,tk): + allv = d.keys() + allv.sort() + for v in allv: + tv = t.get(v) + if self.use(v,tv) and not self.toocommon(v,tv): + f.write('%s -> %s' % ( self.fix(k),self.fix(v) ) ) + self.write_attributes(f,self.edge_attributes(k,v)) + f.write(';\n') + f.write(self.fix(k)) + self.write_attributes(f,self.node_attributes(k,tk)) + f.write(';\n') + f.write('}\n') + + def write_attributes(self,f,a): + if a: + f.write(' [') + f.write(','.join(a)) + f.write(']') + + def node_attributes(self,k,type): + a = [] + a.append('label="%s"' % self.label(k)) + if self.colored: + a.append('fillcolor="%s"' % self.color(k,type)) + else: + a.append('fillcolor=white') + if self.toocommon(k,type): + a.append('peripheries=2') + return a + + def edge_attributes(self,k,v): + a = [] + weight = self.weight(k,v) + if weight!=1: + a.append('weight=%d' % weight) + length = self.alien(k,v) + if length: + a.append('minlen=%d' % length) + return a + + def get_data(self): + t = eval(sys.stdin.read()) + return t['depgraph'],t['types'] + + def get_output_file(self): + return sys.stdout + + def use(self,s,type): + # Return true if this module is interesting and should be drawn. Return false + # if it should be completely omitted. This is a default policy - please override. + if s=='__main__': + return 0 + #if s in ('os','sys','time','__future__','types','re','string'): + if s in ('sys'): + # nearly all modules use all of these... more or less. They add nothing to + # our diagram. + return 0 + if s.startswith('encodings.'): + return 0 + if self.toocommon(s,type): + # A module where we dont want to draw references _to_. Dot doesnt handle these + # well, so it is probably best to not draw them at all. + return 0 + return 1 + + def toocommon(self,s,type): + # Return true if references to this module are uninteresting. Such references + # do not get drawn. This is a default policy - please override. + # + if s=='__main__': + # references *to* __main__ are never interesting. omitting them means + # that main floats to the top of the page + return 1 + #if type==imp.PKG_DIRECTORY: + # # dont draw references to packages. + # return 1 + return 0 + + def weight(self,a,b): + # Return the weight of the dependency from a to b. Higher weights + # usually have shorter straighter edges. Return 1 if it has normal weight. + # A value of 4 is usually good for ensuring that a related pair of modules + # are drawn next to each other. This is a default policy - please override. + # + if b.split('.')[-1].startswith('_'): + # A module that starts with an underscore. You need a special reason to + # import these (for example random imports _random), so draw them close + # together + return 4 + return 1 + + def alien(self,a,b): + # Return non-zero if references to this module are strange, and should be drawn + # extra-long. the value defines the length, in rank. This is also good for putting some + # vertical space between seperate subsystems. This is a default policy - please override. + # + return 0 + + def label(self,s): + # Convert a module name to a formatted node label. This is a default policy - please override. + # + return '\\.\\n'.join(s.split('.')) + + def color(self,s,type): + # Return the node color for this module name. This is a default policy - please override. + # + # Calculate a color systematically based on the hash of the module name. Modules in the + # same package have the same color. Unpackaged modules are grey + t = self.normalise_module_name_for_hash_coloring(s,type) + return self.color_from_name(t) + + def normalise_module_name_for_hash_coloring(self,s,type): + if type==imp.PKG_DIRECTORY: + return s + else: + i = s.rfind('.') + if i<0: + return '' + else: + return s[:i] + + def color_from_name(self,name): + n = md5.md5(name).digest() + hf = float(ord(n[0])+ord(n[1])*0xff)/0xffff + sf = float(ord(n[2]))/0xff + vf = float(ord(n[3]))/0xff + r,g,b = colorsys.hsv_to_rgb(hf, 0.3+0.6*sf, 0.8+0.2*vf) + return '#%02x%02x%02x' % (r*256,g*256,b*256) + + +def main(): + pydepgraphdot().main(sys.argv[1:]) + +if __name__=='__main__': + main() + + + --- python2.7-2.7.15.orig/debian/dh_doclink +++ python2.7-2.7.15/debian/dh_doclink @@ -0,0 +1,28 @@ +#! /bin/sh + +pkg=`echo $1 | sed 's/^-p//'` +target=$2 + +ln -sf $target debian/$pkg/usr/share/doc/$pkg + +f=debian/$pkg.postinst.debhelper +if [ ! -e $f ] || [ "`grep -c '^# dh_doclink' $f`" -eq 0 ]; then +cat >> $f <> $f < /dev/null`; do \ + while rmdir $$d 2> /dev/null; do d=`dirname $$d`; done; \ +done + +exit 0 --- python2.7-2.7.15.orig/debian/idle-PVER.1.in +++ python2.7-2.7.15/debian/idle-PVER.1.in @@ -0,0 +1,104 @@ +.TH IDLE 1 "21 September 2004" +.SH NAME +\fBIDLE\fP \- An Integrated DeveLopment Environment for Python +.SH SYNTAX +.B idle [ \fI-dins\fP ] [ \fI-t title\fP ] [ \fIfile\fP ...] +.PP +.B idle [ \fI-dins\fP ] [ \fI-t title\fP ] ( \fI-c cmd\fP | \fI-r file\fP ) [ \fIarg\fP ...] +.PP +.B idle [ \fI-dins\fP ] [ \fI-t title\fP ] - [ \fIarg\fP ...] +.SH DESCRIPTION +This manual page documents briefly the +.BR idle +command. +This manual page was written for Debian +because the original program does not have a manual page. +For more information, refer to IDLE's help menu. +.PP +.B IDLE +is an Integrated DeveLopment Environment for Python. IDLE is based on +Tkinter, Python's bindings to the Tk widget set. Features are 100% pure +Python, multi-windows with multiple undo and Python colorizing, a Python +shell window subclass, a debugger. IDLE is cross-platform, i.e. it works +on all platforms where Tk is installed. +.LP +.SH OPTIONS +.TP +.B \-h +.PD +Print this help message and exit. +.TP +.B \-n +.PD +Run IDLE without a subprocess (see Help/IDLE Help for details). +.PP +The following options will override the IDLE 'settings' configuration: +.TP +.B \-e +.PD +Open an edit window. +.TP +.B \-i +.PD +Open a shell window. +.PP +The following options imply -i and will open a shell: +.TP +.B \-c cmd +.PD +Run the command in a shell, or +.TP +.B \-r file +.PD +Run script from file. +.PP +.TP +.B \-d +.PD +Enable the debugger. +.TP +.B \-s +.PD +Run $IDLESTARTUP or $PYTHONSTARTUP before anything else. +.TP +.B \-t title +.PD +Set title of shell window. +.PP +A default edit window will be bypassed when -c, -r, or - are used. +.PP +[arg]* and [file]* are passed to the command (-c) or script (-r) in sys.argv[1:]. +.SH EXAMPLES +.TP +idle +.PD +Open an edit window or shell depending on IDLE's configuration. +.TP +idle foo.py foobar.py +.PD +Edit the files, also open a shell if configured to start with shell. +.TP +idle -est "Baz" foo.py +.PD +Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell +window with the title "Baz". +.TP +idle -c "import sys; print sys.argv" "foo" +.PD +Open a shell window and run the command, passing "-c" in sys.argv[0] +and "foo" in sys.argv[1]. +.TP +idle -d -s -r foo.py "Hello World" +.PD +Open a shell window, run a startup script, enable the debugger, and +run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in +sys.argv[1]. +.TP +echo "import sys; print sys.argv" | idle - "foobar" +.PD +Open a shell window, run the script piped in, passing '' in sys.argv[0] +and "foobar" in sys.argv[1]. +.SH SEE ALSO +python(1). +.SH AUTHORS +Various. --- python2.7-2.7.15.orig/debian/idle-PVER.overrides.in +++ python2.7-2.7.15/debian/idle-PVER.overrides.in @@ -0,0 +1,5 @@ +# icon in dependent package +idle-@PVER@ binary: menu-icon-missing + +idle-@PVER@ binary: command-with-path-in-maintainer-script +idle-@PVER@ binary: image-file-in-usr-lib --- python2.7-2.7.15.orig/debian/idle-PVER.postinst.in +++ python2.7-2.7.15/debian/idle-PVER.postinst.in @@ -0,0 +1,32 @@ +#! /bin/sh +# +# postinst script for the Debian idle-@PVER@ package. +# Written 1998 by Gregor Hoffleit . +# + +set -e + +DIRLIST="/usr/lib/python@VER@/idlelib" + +case "$1" in + configure|abort-upgrade|abort-remove|abort-deconfigure) + + for i in $DIRLIST ; do + /usr/bin/@PVER@ /usr/lib/@PVER@/compileall.py -q $i + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config + then + /usr/bin/@PVER@ -O /usr/lib/@PVER@/compileall.py -q $i + fi + done + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; + +esac + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/idle-PVER.postrm.in +++ python2.7-2.7.15/debian/idle-PVER.postrm.in @@ -0,0 +1,11 @@ +#! /bin/sh + +set -e + +if [ "$1" = "purge" ]; then + rm -rf /etc/idle-@PVER@ +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/idle-PVER.prerm.in +++ python2.7-2.7.15/debian/idle-PVER.prerm.in @@ -0,0 +1,17 @@ +#! /bin/sh +# +# sample prerm script for the Debian idle-@PVER@ package. +# Written 1998 by Gregor Hoffleit . +# + +set -e + +PACKAGE=`basename $0 .prerm` + +dpkg --listfiles $PACKAGE | + awk '$0~/\.py$/ {print $0"c\n" $0"o"}' | + xargs rm -f >&2 + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/idle.desktop.in +++ python2.7-2.7.15/debian/idle.desktop.in @@ -0,0 +1,9 @@ +[Desktop Entry] +Name=IDLE (using Python-@VER@) +Comment=Integrated Development Environment for Python (using Python-@VER@) +Exec=/usr/bin/idle-@PVER@ +Icon=/usr/share/pixmaps/@PVER@.xpm +Terminal=false +Type=Application +Categories=Application;Development; +StartupNotify=true --- python2.7-2.7.15.orig/debian/libPVER-dbg.overrides.in +++ python2.7-2.7.15/debian/libPVER-dbg.overrides.in @@ -0,0 +1,7 @@ +lib@PVER@-dbg binary: package-name-doesnt-match-sonames +lib@PVER@-dbg binary: non-dev-pkg-with-shlib-symlink + +lib@PVER@-dbg binary: arch-dependent-file-not-in-arch-specific-directory + +# pointless lintian ... +lib@PVER@-dbg binary: hardening-no-fortify-functions --- python2.7-2.7.15.orig/debian/libPVER-dbg.postinst.in +++ python2.7-2.7.15/debian/libPVER-dbg.postinst.in @@ -0,0 +1,12 @@ +#! /bin/sh + +set -e + +if [ "$1" = configure ]; then + # _sysconfigdata_d.py now found in the platform directory + rm -f /usr/lib/python2.7/_sysconfigdata_d.py[co] +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/libPVER-dbg.prerm.in +++ python2.7-2.7.15/debian/libPVER-dbg.prerm.in @@ -0,0 +1,23 @@ +#! /bin/sh + +set -e + +case "$1" in + remove) + dpkg -L lib@PVER@-dbg@HOST_QUAL@ \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 + ;; + upgrade) + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.15.orig/debian/libPVER-dbg.symbols.in +++ python2.7-2.7.15/debian/libPVER-dbg.symbols.in @@ -0,0 +1,33 @@ +libpython@VER@_d.so.1.0 libpython@VER@-dbg #MINVER# + Py_InitModule4TraceRefs@Base @VER@ +#include "libpython.symbols" + _PyDict_Dummy@Base @VER@ + _PyMem_DebugFree@Base @VER@ + _PyMem_DebugMalloc@Base @VER@ + _PyMem_DebugRealloc@Base @VER@ + _PyObject_DebugCheckAddress@Base @VER@ + _PyObject_DebugCheckAddressApi@Base @VER@ + _PyObject_DebugDumpAddress@Base @VER@ + _PyObject_DebugFree@Base @VER@ + _PyObject_DebugFreeApi@Base @VER@ + _PyObject_DebugMalloc@Base @VER@ + _PyObject_DebugMallocApi@Base @VER@ + _PyObject_DebugMallocStats@Base @VER@ + _PyObject_DebugRealloc@Base @VER@ + _PyObject_DebugReallocApi@Base @VER@ + _PySet_Dummy@Base @VER@ + _Py_AddToAllObjects@Base @VER@ + _Py_Dealloc@Base @VER@ + _Py_ForgetReference@Base @VER@ + _Py_GetObjects@Base @VER@ + _Py_GetRefTotal@Base @VER@ + _Py_HashSecret_Initialized@Base @VER@ + _Py_NegativeRefcount@Base @VER@ + _Py_NewReference@Base @VER@ + _Py_PrintReferenceAddresses@Base @VER@ + _Py_PrintReferences@Base @VER@ + _Py_RefTotal@Base @VER@ + _Py_dumptree@Base @VER@ + _Py_printtree@Base @VER@ + _Py_showtree@Base @VER@ + _Py_tok_dump@Base @VER@ --- python2.7-2.7.15.orig/debian/libPVER-dev.overrides.in +++ python2.7-2.7.15/debian/libPVER-dev.overrides.in @@ -0,0 +1,3 @@ +lib@PVER@-dev binary: python-script-but-no-python-dep + +lib@PVER@-dev binary: arch-dependent-file-not-in-arch-specific-directory --- python2.7-2.7.15.orig/debian/libPVER-minimal.overrides.in +++ python2.7-2.7.15/debian/libPVER-minimal.overrides.in @@ -0,0 +1 @@ +lib@PVER@-minimal binary: python-script-but-no-python-dep --- python2.7-2.7.15.orig/debian/libPVER-minimal.postinst.in +++ python2.7-2.7.15/debian/libPVER-minimal.postinst.in @@ -0,0 +1,17 @@ +#! /bin/sh + +set -e + +if [ ! -f /etc/@PVER@/sitecustomize.py ]; then + cat <<-EOF + # Empty sitecustomize.py to avoid a dangling symlink +EOF +fi + +if [ "$1" = configure ]; then + rm -f /etc/@PVER@/cert-verification.conf +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/libPVER-minimal.postrm.in +++ python2.7-2.7.15/debian/libPVER-minimal.postrm.in @@ -0,0 +1,27 @@ +#! /bin/sh + +set -e + +if [ "$1" = "remove" ]; then + pc=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' -W lib@PVER@-minimal \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + find /usr/lib/@PVER@ -name '*.py[co]' -print0 | xargs -r0 rm -f + fi +fi + +if [ "$1" = "purge" ]; then + pc=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' -W lib@PVER@-minimal \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + rm -f /etc/@PVER@/site.py /etc/@PVER@/sitecustomize.py + if [ -d /etc/@PVER@ ]; then + rmdir --ignore-fail-on-non-empty /etc/@PVER@ 2>/dev/null + fi + fi + rm -f /etc/@PVER@/cert-verification.conf +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.15.orig/debian/libPVER-minimal.prerm.in +++ python2.7-2.7.15/debian/libPVER-minimal.prerm.in @@ -0,0 +1,35 @@ +#! /bin/sh + +set -e + +remove_bytecode() +{ + pkg=$1 + dpkg -L $1 \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 +} + +case "$1" in + remove) + pc=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' -W lib@PVER@-minimal \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + remove_bytecode lib@PVER@-minimal@HOST_QUAL@ + fi + ;; + upgrade) + remove_bytecode lib@PVER@-minimal@HOST_QUAL@ + # byte compilation in @PVER@-minimal postinst, strict dependency + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.15.orig/debian/libPVER-stdlib.overrides.in +++ python2.7-2.7.15/debian/libPVER-stdlib.overrides.in @@ -0,0 +1,14 @@ +# idlelib images +lib@PVER@-stdlib binary: image-file-in-usr-lib + +# license file referred by the standard library +lib@PVER@-stdlib binary: extra-license-file + +# template files +lib@PVER@-stdlib binary: interpreter-not-absolute usr/lib/python3.3/venv/scripts/posix/pydoc #!__VENV_PYTHON__ +lib@PVER@-stdlib binary: unusual-interpreter usr/lib/python3.3/venv/scripts/posix/pydoc #!__VENV_PYTHON__ + +# the split is the reason for that +lib@PVER@-stdlib binary: python-script-but-no-python-dep + +lib@PVER@-stdlib binary: arch-dependent-file-not-in-arch-specific-directory --- python2.7-2.7.15.orig/debian/libPVER-stdlib.prerm.in +++ python2.7-2.7.15/debian/libPVER-stdlib.prerm.in @@ -0,0 +1,35 @@ +#! /bin/sh + +set -e + +remove_bytecode() +{ + pkg=$1 + dpkg -L $1 \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 +} + +case "$1" in + remove) + pc=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' -W lib@PVER@-stdlib \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + remove_bytecode lib@PVER@-stdlib@HOST_QUAL@ + fi + ;; + upgrade) + remove_bytecode lib@PVER@-stdlib@HOST_QUAL@ + # byte compilation in @PVER@ postinst, strict dependency + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.15.orig/debian/libPVER-testsuite.overrides.in +++ python2.7-2.7.15/debian/libPVER-testsuite.overrides.in @@ -0,0 +1,4 @@ +lib@PVER@-testsuite binary: python-script-but-no-python-dep +lib@PVER@-testsuite binary: image-file-in-usr-lib +lib@PVER@-testsuite binary: privacy-breach-generic +lib@PVER@-testsuite binary: command-with-path-in-maintainer-script --- python2.7-2.7.15.orig/debian/libPVER-testsuite.prerm.in +++ python2.7-2.7.15/debian/libPVER-testsuite.prerm.in @@ -0,0 +1,30 @@ +#! /bin/sh + +set -e + +remove_bytecode() +{ + pkg=$1 + dpkg -L $1 \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 +} + +case "$1" in + remove) + remove_bytecode lib@PVER@-testsuite + ;; + upgrade) + remove_bytecode lib@PVER@-testsuite + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.15.orig/debian/libPVER.overrides.in +++ python2.7-2.7.15/debian/libPVER.overrides.in @@ -0,0 +1 @@ +lib@PVER@ binary: package-name-doesnt-match-sonames --- python2.7-2.7.15.orig/debian/libPVER.symbols.in +++ python2.7-2.7.15/debian/libPVER.symbols.in @@ -0,0 +1,3 @@ +libpython@VER@.so.1.0 libpython@VER@ #MINVER# + Py_InitModule4@Base @VER@ +#include "libpython.symbols" --- python2.7-2.7.15.orig/debian/libpython.symbols.in +++ python2.7-2.7.15/debian/libpython.symbols.in @@ -0,0 +1,1351 @@ + PyAST_Check@Base @VER@ + PyAST_Compile@Base @VER@ + PyAST_FromNode@Base @VER@ + PyAST_mod2obj@Base @VER@ + PyAST_obj2mod@Base @VER@ + PyArena_AddPyObject@Base @VER@ + PyArena_Free@Base @VER@ + PyArena_Malloc@Base @VER@ + PyArena_New@Base @VER@ + PyArg_Parse@Base @VER@ + PyArg_ParseTuple@Base @VER@ + PyArg_ParseTupleAndKeywords@Base @VER@ + PyArg_UnpackTuple@Base @VER@ + PyArg_VaParse@Base @VER@ + PyArg_VaParseTupleAndKeywords@Base @VER@ + PyBaseObject_Type@Base @VER@ + PyBaseString_Type@Base @VER@ + PyBool_FromLong@Base @VER@ + PyBool_Type@Base @VER@ + PyBuffer_FillContiguousStrides@Base @VER@ + PyBuffer_FillInfo@Base @VER@ + PyBuffer_FromContiguous@Base @VER@ + PyBuffer_FromMemory@Base @VER@ + PyBuffer_FromObject@Base @VER@ + PyBuffer_FromReadWriteMemory@Base @VER@ + PyBuffer_FromReadWriteObject@Base @VER@ + PyBuffer_GetPointer@Base @VER@ + PyBuffer_IsContiguous@Base @VER@ + PyBuffer_New@Base @VER@ + PyBuffer_Release@Base @VER@ + PyBuffer_ToContiguous@Base @VER@ + PyBuffer_Type@Base @VER@ + (optional)PyBufferedIOBase_Type@Base @VER@ + (optional)PyBufferedRWPair_Type@Base @VER@ + (optional)PyBufferedRandom_Type@Base @VER@ + (optional)PyBufferedReader_Type@Base @VER@ + (optional)PyBufferedWriter_Type@Base @VER@ + PyByteArrayIter_Type@Base @VER@ + PyByteArray_AsString@Base @VER@ + PyByteArray_Concat@Base @VER@ + PyByteArray_Fini@Base @VER@ + PyByteArray_FromObject@Base @VER@ + PyByteArray_FromStringAndSize@Base @VER@ + PyByteArray_Init@Base @VER@ + PyByteArray_Resize@Base @VER@ + PyByteArray_Size@Base @VER@ + PyByteArray_Type@Base @VER@ + (optional)PyBytesIO_Type@Base @VER@ + PyCFunction_Call@Base @VER@ + PyCFunction_ClearFreeList@Base @VER@ + PyCFunction_Fini@Base @VER@ + PyCFunction_GetFlags@Base @VER@ + PyCFunction_GetFunction@Base @VER@ + PyCFunction_GetSelf@Base @VER@ + PyCFunction_New@Base @VER@ + PyCFunction_NewEx@Base @VER@ + PyCFunction_Type@Base @VER@ + PyCObject_AsVoidPtr@Base @VER@ + PyCObject_FromVoidPtr@Base @VER@ + PyCObject_FromVoidPtrAndDesc@Base @VER@ + PyCObject_GetDesc@Base @VER@ + PyCObject_Import@Base @VER@ + PyCObject_SetVoidPtr@Base @VER@ + PyCObject_Type@Base @VER@ + PyCallIter_New@Base @VER@ + PyCallIter_Type@Base @VER@ + PyCallable_Check@Base @VER@ + PyCapsule_GetContext@Base @VER@ + PyCapsule_GetDestructor@Base @VER@ + PyCapsule_GetName@Base @VER@ + PyCapsule_GetPointer@Base @VER@ + PyCapsule_Import@Base @VER@ + PyCapsule_IsValid@Base @VER@ + PyCapsule_New@Base @VER@ + PyCapsule_SetContext@Base @VER@ + PyCapsule_SetDestructor@Base @VER@ + PyCapsule_SetName@Base @VER@ + PyCapsule_SetPointer@Base @VER@ + PyCapsule_Type@Base @VER@ + PyCell_Get@Base @VER@ + PyCell_New@Base @VER@ + PyCell_Set@Base @VER@ + PyCell_Type@Base @VER@ + PyClassMethod_New@Base @VER@ + PyClassMethod_Type@Base @VER@ + PyClass_IsSubclass@Base @VER@ + PyClass_New@Base @VER@ + PyClass_Type@Base @VER@ + PyCode_Addr2Line@Base @VER@ + PyCode_New@Base @VER@ + PyCode_NewEmpty@Base @VER@ + PyCode_Optimize@Base @VER@ + PyCode_Type@Base @VER@ + PyCodec_BackslashReplaceErrors@Base @VER@ + PyCodec_Decode@Base @VER@ + PyCodec_Decoder@Base @VER@ + PyCodec_Encode@Base @VER@ + PyCodec_Encoder@Base @VER@ + PyCodec_IgnoreErrors@Base @VER@ + PyCodec_IncrementalDecoder@Base @VER@ + PyCodec_IncrementalEncoder@Base @VER@ + PyCodec_LookupError@Base @VER@ + PyCodec_Register@Base @VER@ + PyCodec_RegisterError@Base @VER@ + PyCodec_ReplaceErrors@Base @VER@ + PyCodec_StreamReader@Base @VER@ + PyCodec_StreamWriter@Base @VER@ + PyCodec_StrictErrors@Base @VER@ + PyCodec_XMLCharRefReplaceErrors@Base @VER@ + PyComplex_AsCComplex@Base @VER@ + PyComplex_FromCComplex@Base @VER@ + PyComplex_FromDoubles@Base @VER@ + PyComplex_ImagAsDouble@Base @VER@ + PyComplex_RealAsDouble@Base @VER@ + PyComplex_Type@Base @VER@ + PyDescr_NewClassMethod@Base @VER@ + PyDescr_NewGetSet@Base @VER@ + PyDescr_NewMember@Base @VER@ + PyDescr_NewMethod@Base @VER@ + PyDescr_NewWrapper@Base @VER@ + PyDictItems_Type@Base @VER@ + PyDictIterItem_Type@Base @VER@ + PyDictIterKey_Type@Base @VER@ + PyDictIterValue_Type@Base @VER@ + PyDictKeys_Type@Base @VER@ + PyDictProxy_New@Base @VER@ + PyDictProxy_Type@Base @VER@ + PyDictValues_Type@Base @VER@ + PyDict_Clear@Base @VER@ + PyDict_Contains@Base @VER@ + PyDict_Copy@Base @VER@ + PyDict_DelItem@Base @VER@ + PyDict_DelItemString@Base @VER@ + PyDict_Fini@Base @VER@ + PyDict_GetItem@Base @VER@ + PyDict_GetItemString@Base @VER@ + PyDict_Items@Base @VER@ + PyDict_Keys@Base @VER@ + PyDict_Merge@Base @VER@ + PyDict_MergeFromSeq2@Base @VER@ + PyDict_New@Base @VER@ + PyDict_Next@Base @VER@ + PyDict_SetItem@Base @VER@ + PyDict_SetItemString@Base @VER@ + PyDict_Size@Base @VER@ + PyDict_Type@Base @VER@ + PyDict_Update@Base @VER@ + PyDict_Values@Base @VER@ + PyEllipsis_Type@Base @VER@ + PyEnum_Type@Base @VER@ + PyErr_BadArgument@Base @VER@ + PyErr_BadInternalCall@Base @VER@ + PyErr_CheckSignals@Base @VER@ + PyErr_Clear@Base @VER@ + PyErr_Display@Base @VER@ + PyErr_ExceptionMatches@Base @VER@ + PyErr_Fetch@Base @VER@ + PyErr_Format@Base @VER@ + PyErr_GivenExceptionMatches@Base @VER@ + PyErr_NewException@Base @VER@ + PyErr_NewExceptionWithDoc@Base @VER@ + PyErr_NoMemory@Base @VER@ + PyErr_NormalizeException@Base @VER@ + PyErr_Occurred@Base @VER@ + PyErr_Print@Base @VER@ + PyErr_PrintEx@Base @VER@ + PyErr_ProgramText@Base @VER@ + PyErr_Restore@Base @VER@ + PyErr_SetFromErrno@Base @VER@ + PyErr_SetFromErrnoWithFilename@Base @VER@ + PyErr_SetFromErrnoWithFilenameObject@Base @VER@ + PyErr_SetInterrupt@Base @VER@ + PyErr_SetNone@Base @VER@ + PyErr_SetObject@Base @VER@ + PyErr_SetString@Base @VER@ + PyErr_SyntaxLocation@Base @VER@ + PyErr_Warn@Base @VER@ + PyErr_WarnEx@Base @VER@ + PyErr_WarnExplicit@Base @VER@ + PyErr_WriteUnraisable@Base @VER@ + PyEval_AcquireLock@Base @VER@ + PyEval_AcquireThread@Base @VER@ + PyEval_CallFunction@Base @VER@ + PyEval_CallMethod@Base @VER@ + PyEval_CallObjectWithKeywords@Base @VER@ + PyEval_EvalCode@Base @VER@ + PyEval_EvalCodeEx@Base @VER@ + PyEval_EvalFrame@Base @VER@ + PyEval_EvalFrameEx@Base @VER@ + PyEval_GetBuiltins@Base @VER@ + PyEval_GetCallStats@Base @VER@ + PyEval_GetFrame@Base @VER@ + PyEval_GetFuncDesc@Base @VER@ + PyEval_GetFuncName@Base @VER@ + PyEval_GetGlobals@Base @VER@ + PyEval_GetLocals@Base @VER@ + PyEval_GetRestricted@Base @VER@ + PyEval_InitThreads@Base @VER@ + PyEval_MergeCompilerFlags@Base @VER@ + PyEval_ReInitThreads@Base @VER@ + PyEval_ReleaseLock@Base @VER@ + PyEval_ReleaseThread@Base @VER@ + PyEval_RestoreThread@Base @VER@ + PyEval_SaveThread@Base @VER@ + PyEval_SetProfile@Base @VER@ + PyEval_SetTrace@Base @VER@ + PyEval_ThreadsInitialized@Base @VER@ + PyExc_ArithmeticError@Base @VER@ + PyExc_AssertionError@Base @VER@ + PyExc_AttributeError@Base @VER@ + PyExc_BaseException@Base @VER@ + (optional)PyExc_BlockingIOError@Base @VER@ + PyExc_BufferError@Base @VER@ + PyExc_BytesWarning@Base @VER@ + PyExc_DeprecationWarning@Base @VER@ + PyExc_EOFError@Base @VER@ + PyExc_EnvironmentError@Base @VER@ + PyExc_Exception@Base @VER@ + PyExc_FloatingPointError@Base @VER@ + PyExc_FutureWarning@Base @VER@ + PyExc_GeneratorExit@Base @VER@ + PyExc_IOError@Base @VER@ + PyExc_ImportError@Base @VER@ + PyExc_ImportWarning@Base @VER@ + PyExc_IndentationError@Base @VER@ + PyExc_IndexError@Base @VER@ + PyExc_KeyError@Base @VER@ + PyExc_KeyboardInterrupt@Base @VER@ + PyExc_LookupError@Base @VER@ + PyExc_MemoryError@Base @VER@ + PyExc_MemoryErrorInst@Base @VER@ + PyExc_NameError@Base @VER@ + PyExc_NotImplementedError@Base @VER@ + PyExc_OSError@Base @VER@ + PyExc_OverflowError@Base @VER@ + PyExc_PendingDeprecationWarning@Base @VER@ + PyExc_RecursionErrorInst@Base @VER@ + PyExc_ReferenceError@Base @VER@ + PyExc_RuntimeError@Base @VER@ + PyExc_RuntimeWarning@Base @VER@ + PyExc_StandardError@Base @VER@ + PyExc_StopIteration@Base @VER@ + PyExc_SyntaxError@Base @VER@ + PyExc_SyntaxWarning@Base @VER@ + PyExc_SystemError@Base @VER@ + PyExc_SystemExit@Base @VER@ + PyExc_TabError@Base @VER@ + PyExc_TypeError@Base @VER@ + PyExc_UnboundLocalError@Base @VER@ + PyExc_UnicodeDecodeError@Base @VER@ + PyExc_UnicodeEncodeError@Base @VER@ + PyExc_UnicodeError@Base @VER@ + PyExc_UnicodeTranslateError@Base @VER@ + PyExc_UnicodeWarning@Base @VER@ + PyExc_UserWarning@Base @VER@ + PyExc_ValueError@Base @VER@ + PyExc_Warning@Base @VER@ + PyExc_ZeroDivisionError@Base @VER@ + (optional)PyFileIO_Type@Base @VER@ + PyFile_AsFile@Base @VER@ + PyFile_DecUseCount@Base @VER@ + PyFile_FromFile@Base @VER@ + PyFile_FromString@Base @VER@ + PyFile_GetLine@Base @VER@ + PyFile_IncUseCount@Base @VER@ + PyFile_Name@Base @VER@ + PyFile_SetBufSize@Base @VER@ + PyFile_SetEncoding@Base @VER@ + PyFile_SetEncodingAndErrors@Base @VER@ + PyFile_SoftSpace@Base @VER@ + PyFile_Type@Base @VER@ + PyFile_WriteObject@Base @VER@ + PyFile_WriteString@Base @VER@ + PyFloat_AsDouble@Base @VER@ + PyFloat_AsReprString@Base @VER@ + PyFloat_AsString@Base @VER@ + PyFloat_ClearFreeList@Base @VER@ + PyFloat_Fini@Base @VER@ + PyFloat_FromDouble@Base @VER@ + PyFloat_FromString@Base @VER@ + PyFloat_GetInfo@Base @VER@ + PyFloat_GetMax@Base @VER@ + PyFloat_GetMin@Base @VER@ + PyFloat_Type@Base @VER@ + PyFrame_BlockPop@Base @VER@ + PyFrame_BlockSetup@Base @VER@ + PyFrame_ClearFreeList@Base @VER@ + PyFrame_FastToLocals@Base @VER@ + PyFrame_Fini@Base @VER@ + PyFrame_GetLineNumber@Base @VER@ + PyFrame_LocalsToFast@Base @VER@ + PyFrame_New@Base @VER@ + PyFrame_Type@Base @VER@ + PyFrozenSet_New@Base @VER@ + PyFrozenSet_Type@Base @VER@ + PyFunction_GetClosure@Base @VER@ + PyFunction_GetCode@Base @VER@ + PyFunction_GetDefaults@Base @VER@ + PyFunction_GetGlobals@Base @VER@ + PyFunction_GetModule@Base @VER@ + PyFunction_New@Base @VER@ + PyFunction_SetClosure@Base @VER@ + PyFunction_SetDefaults@Base @VER@ + PyFunction_Type@Base @VER@ + PyFuture_FromAST@Base @VER@ + PyGC_Collect@Base @VER@ + PyGILState_Ensure@Base @VER@ + PyGILState_GetThisThreadState@Base @VER@ + PyGILState_Release@Base @VER@ + PyGen_NeedsFinalizing@Base @VER@ + PyGen_New@Base @VER@ + PyGen_Type@Base @VER@ + PyGetSetDescr_Type@Base @VER@ + PyGrammar_AddAccelerators@Base @VER@ + PyGrammar_FindDFA@Base @VER@ + PyGrammar_LabelRepr@Base @VER@ + PyGrammar_RemoveAccelerators@Base @VER@ + (optional)PyIOBase_Type@Base @VER@ + PyImport_AddModule@Base @VER@ + PyImport_AppendInittab@Base @VER@ + PyImport_Cleanup@Base @VER@ + PyImport_ExecCodeModule@Base @VER@ + PyImport_ExecCodeModuleEx@Base @VER@ + PyImport_ExtendInittab@Base @VER@ + PyImport_FrozenModules@Base @VER@ + PyImport_GetImporter@Base @VER@ + PyImport_GetMagicNumber@Base @VER@ + PyImport_GetModuleDict@Base @VER@ + PyImport_Import@Base @VER@ + PyImport_ImportFrozenModule@Base @VER@ + PyImport_ImportModule@Base @VER@ + PyImport_ImportModuleLevel@Base @VER@ + PyImport_ImportModuleNoBlock@Base @VER@ + PyImport_Inittab@Base @VER@ + PyImport_ReloadModule@Base @VER@ + (optional)PyIncrementalNewlineDecoder_Type@Base @VER@ + PyInstance_New@Base @VER@ + PyInstance_NewRaw@Base @VER@ + PyInstance_Type@Base @VER@ + PyInt_AsLong@Base @VER@ + PyInt_AsSsize_t@Base @VER@ + PyInt_AsUnsignedLongLongMask@Base @VER@ + PyInt_AsUnsignedLongMask@Base @VER@ + PyInt_ClearFreeList@Base @VER@ + PyInt_Fini@Base @VER@ + PyInt_FromLong@Base @VER@ + PyInt_FromSize_t@Base @VER@ + PyInt_FromSsize_t@Base @VER@ + PyInt_FromString@Base @VER@ + PyInt_FromUnicode@Base @VER@ + PyInt_GetMax@Base @VER@ + PyInt_Type@Base @VER@ + PyInterpreterState_Clear@Base @VER@ + PyInterpreterState_Delete@Base @VER@ + PyInterpreterState_Head@Base @VER@ + PyInterpreterState_New@Base @VER@ + PyInterpreterState_Next@Base @VER@ + PyInterpreterState_ThreadHead@Base @VER@ + PyIter_Next@Base @VER@ + PyListIter_Type@Base @VER@ + PyListRevIter_Type@Base @VER@ + PyList_Append@Base @VER@ + PyList_AsTuple@Base @VER@ + PyList_Fini@Base @VER@ + PyList_GetItem@Base @VER@ + PyList_GetSlice@Base @VER@ + PyList_Insert@Base @VER@ + PyList_New@Base @VER@ + PyList_Reverse@Base @VER@ + PyList_SetItem@Base @VER@ + PyList_SetSlice@Base @VER@ + PyList_Size@Base @VER@ + PyList_Sort@Base @VER@ + PyList_Type@Base @VER@ + PyLong_AsDouble@Base @VER@ + PyLong_AsLong@Base @VER@ + PyLong_AsLongAndOverflow@Base @VER@ + PyLong_AsLongLong@Base @VER@ + PyLong_AsLongLongAndOverflow@Base @VER@ + PyLong_AsSsize_t@Base @VER@ + PyLong_AsUnsignedLong@Base @VER@ + PyLong_AsUnsignedLongLong@Base @VER@ + PyLong_AsUnsignedLongLongMask@Base @VER@ + PyLong_AsUnsignedLongMask@Base @VER@ + PyLong_AsVoidPtr@Base @VER@ + PyLong_FromDouble@Base @VER@ + PyLong_FromLong@Base @VER@ + PyLong_FromLongLong@Base @VER@ + PyLong_FromSize_t@Base @VER@ + PyLong_FromSsize_t@Base @VER@ + PyLong_FromString@Base @VER@ + PyLong_FromUnicode@Base @VER@ + PyLong_FromUnsignedLong@Base @VER@ + PyLong_FromUnsignedLongLong@Base @VER@ + PyLong_FromVoidPtr@Base @VER@ + PyLong_GetInfo@Base @VER@ + PyLong_Type@Base @VER@ + PyMapping_Check@Base @VER@ + PyMapping_GetItemString@Base @VER@ + PyMapping_HasKey@Base @VER@ + PyMapping_HasKeyString@Base @VER@ + PyMapping_Length@Base @VER@ + PyMapping_SetItemString@Base @VER@ + PyMapping_Size@Base @VER@ + PyMarshal_Init@Base @VER@ + PyMarshal_ReadLastObjectFromFile@Base @VER@ + PyMarshal_ReadLongFromFile@Base @VER@ + PyMarshal_ReadObjectFromFile@Base @VER@ + PyMarshal_ReadObjectFromString@Base @VER@ + PyMarshal_ReadShortFromFile@Base @VER@ + PyMarshal_WriteLongToFile@Base @VER@ + PyMarshal_WriteObjectToFile@Base @VER@ + PyMarshal_WriteObjectToString@Base @VER@ + PyMem_Free@Base @VER@ + PyMem_Malloc@Base @VER@ + PyMem_Realloc@Base @VER@ + PyMemberDescr_Type@Base @VER@ + PyMember_Get@Base @VER@ + PyMember_GetOne@Base @VER@ + PyMember_Set@Base @VER@ + PyMember_SetOne@Base @VER@ + PyMemoryView_FromBuffer@Base @VER@ + PyMemoryView_FromObject@Base @VER@ + PyMemoryView_GetContiguous@Base @VER@ + PyMemoryView_Type@Base @VER@ + PyMethod_Class@Base @VER@ + PyMethod_ClearFreeList@Base @VER@ + PyMethod_Fini@Base @VER@ + PyMethod_Function@Base @VER@ + PyMethod_New@Base @VER@ + PyMethod_Self@Base @VER@ + PyMethod_Type@Base @VER@ + PyModule_AddIntConstant@Base @VER@ + PyModule_AddObject@Base @VER@ + PyModule_AddStringConstant@Base @VER@ + PyModule_GetDict@Base @VER@ + PyModule_GetFilename@Base @VER@ + PyModule_GetName@Base @VER@ + PyModule_GetWarningsModule@Base @VER@ + PyModule_New@Base @VER@ + PyModule_Type@Base @VER@ + PyNode_AddChild@Base @VER@ + PyNode_Compile@Base @VER@ + PyNode_Free@Base @VER@ + PyNode_ListTree@Base @VER@ + PyNode_New@Base @VER@ + PyNullImporter_Type@Base @VER@ + PyNumber_Absolute@Base @VER@ + PyNumber_Add@Base @VER@ + PyNumber_And@Base @VER@ + (optional)PyNumber_AsOff_t@Base @VER@ + PyNumber_AsSsize_t@Base @VER@ + PyNumber_Check@Base @VER@ + PyNumber_Coerce@Base @VER@ + PyNumber_CoerceEx@Base @VER@ + PyNumber_Divide@Base @VER@ + PyNumber_Divmod@Base @VER@ + PyNumber_Float@Base @VER@ + PyNumber_FloorDivide@Base @VER@ + PyNumber_InPlaceAdd@Base @VER@ + PyNumber_InPlaceAnd@Base @VER@ + PyNumber_InPlaceDivide@Base @VER@ + PyNumber_InPlaceFloorDivide@Base @VER@ + PyNumber_InPlaceLshift@Base @VER@ + PyNumber_InPlaceMultiply@Base @VER@ + PyNumber_InPlaceOr@Base @VER@ + PyNumber_InPlacePower@Base @VER@ + PyNumber_InPlaceRemainder@Base @VER@ + PyNumber_InPlaceRshift@Base @VER@ + PyNumber_InPlaceSubtract@Base @VER@ + PyNumber_InPlaceTrueDivide@Base @VER@ + PyNumber_InPlaceXor@Base @VER@ + PyNumber_Index@Base @VER@ + PyNumber_Int@Base @VER@ + PyNumber_Invert@Base @VER@ + PyNumber_Long@Base @VER@ + PyNumber_Lshift@Base @VER@ + PyNumber_Multiply@Base @VER@ + PyNumber_Negative@Base @VER@ + PyNumber_Or@Base @VER@ + PyNumber_Positive@Base @VER@ + PyNumber_Power@Base @VER@ + PyNumber_Remainder@Base @VER@ + PyNumber_Rshift@Base @VER@ + PyNumber_Subtract@Base @VER@ + PyNumber_ToBase@Base @VER@ + PyNumber_TrueDivide@Base @VER@ + PyNumber_Xor@Base @VER@ + PyOS_AfterFork@Base @VER@ + PyOS_FiniInterrupts@Base @VER@ + PyOS_InitInterrupts@Base @VER@ + PyOS_InputHook@Base @VER@ + PyOS_InterruptOccurred@Base @VER@ + PyOS_Readline@Base @VER@ + PyOS_ReadlineFunctionPointer@Base @VER@ + PyOS_StdioReadline@Base @VER@ + PyOS_ascii_atof@Base @VER@ + PyOS_ascii_formatd@Base @VER@ + PyOS_ascii_strtod@Base @VER@ + PyOS_double_to_string@Base @VER@ + PyOS_getsig@Base @VER@ + PyOS_mystricmp@Base @VER@ + PyOS_mystrnicmp@Base @VER@ + PyOS_setsig@Base @VER@ + PyOS_snprintf@Base @VER@ + PyOS_string_to_double@Base @VER@ + PyOS_strtol@Base @VER@ + PyOS_strtoul@Base @VER@ + PyOS_vsnprintf@Base @VER@ + PyObject_AsCharBuffer@Base @VER@ + PyObject_AsFileDescriptor@Base @VER@ + PyObject_AsReadBuffer@Base @VER@ + PyObject_AsWriteBuffer@Base @VER@ + PyObject_Call@Base @VER@ + PyObject_CallFunction@Base @VER@ + PyObject_CallFunctionObjArgs@Base @VER@ + PyObject_CallMethod@Base @VER@ + PyObject_CallMethodObjArgs@Base @VER@ + PyObject_CallObject@Base @VER@ + PyObject_CheckReadBuffer@Base @VER@ + PyObject_ClearWeakRefs@Base @VER@ + PyObject_Cmp@Base @VER@ + PyObject_Compare@Base @VER@ + PyObject_CopyData@Base @VER@ + PyObject_DelItem@Base @VER@ + PyObject_DelItemString@Base @VER@ + PyObject_Dir@Base @VER@ + PyObject_Format@Base @VER@ + PyObject_Free@Base @VER@ + PyObject_GC_Del@Base @VER@ + PyObject_GC_Track@Base @VER@ + PyObject_GC_UnTrack@Base @VER@ + PyObject_GenericGetAttr@Base @VER@ + PyObject_GenericSetAttr@Base @VER@ + PyObject_GetAttr@Base @VER@ + PyObject_GetAttrString@Base @VER@ + PyObject_GetBuffer@Base @VER@ + PyObject_GetItem@Base @VER@ + PyObject_GetIter@Base @VER@ + PyObject_HasAttr@Base @VER@ + PyObject_HasAttrString@Base @VER@ + PyObject_Hash@Base @VER@ + PyObject_HashNotImplemented@Base @VER@ + PyObject_Init@Base @VER@ + PyObject_InitVar@Base @VER@ + PyObject_IsInstance@Base @VER@ + PyObject_IsSubclass@Base @VER@ + PyObject_IsTrue@Base @VER@ + PyObject_Length@Base @VER@ + PyObject_Malloc@Base @VER@ + PyObject_Not@Base @VER@ + PyObject_Print@Base @VER@ + PyObject_Realloc@Base @VER@ + PyObject_Repr@Base @VER@ + PyObject_RichCompare@Base @VER@ + PyObject_RichCompareBool@Base @VER@ + PyObject_SelfIter@Base @VER@ + PyObject_SetAttr@Base @VER@ + PyObject_SetAttrString@Base @VER@ + PyObject_SetItem@Base @VER@ + PyObject_Size@Base @VER@ + PyObject_Str@Base @VER@ + PyObject_Type@Base @VER@ + PyObject_Unicode@Base @VER@ + PyParser_ASTFromFile@Base @VER@ + PyParser_ASTFromString@Base @VER@ + PyParser_AddToken@Base @VER@ + PyParser_Delete@Base @VER@ + PyParser_New@Base @VER@ + PyParser_ParseFile@Base @VER@ + PyParser_ParseFileFlags@Base @VER@ + PyParser_ParseFileFlagsEx@Base @VER@ + PyParser_ParseString@Base @VER@ + PyParser_ParseStringFlags@Base @VER@ + PyParser_ParseStringFlagsFilename@Base @VER@ + PyParser_ParseStringFlagsFilenameEx@Base @VER@ + PyParser_SetError@Base @VER@ + PyParser_SimpleParseFile@Base @VER@ + PyParser_SimpleParseFileFlags@Base @VER@ + PyParser_SimpleParseString@Base @VER@ + PyParser_SimpleParseStringFilename@Base @VER@ + PyParser_SimpleParseStringFlags@Base @VER@ + PyParser_SimpleParseStringFlagsFilename@Base @VER@ + PyProperty_Type@Base @VER@ + PyRange_Type@Base @VER@ + (optional)PyRawIOBase_Type@Base @VER@ + PyReversed_Type@Base @VER@ + PyRun_AnyFile@Base @VER@ + PyRun_AnyFileEx@Base @VER@ + PyRun_AnyFileExFlags@Base @VER@ + PyRun_AnyFileFlags@Base @VER@ + PyRun_File@Base @VER@ + PyRun_FileEx@Base @VER@ + PyRun_FileExFlags@Base @VER@ + PyRun_FileFlags@Base @VER@ + PyRun_InteractiveLoop@Base @VER@ + PyRun_InteractiveLoopFlags@Base @VER@ + PyRun_InteractiveOne@Base @VER@ + PyRun_InteractiveOneFlags@Base @VER@ + PyRun_SimpleFile@Base @VER@ + PyRun_SimpleFileEx@Base @VER@ + PyRun_SimpleFileExFlags@Base @VER@ + PyRun_SimpleString@Base @VER@ + PyRun_SimpleStringFlags@Base @VER@ + PyRun_String@Base @VER@ + PyRun_StringFlags@Base @VER@ + PySTEntry_Type@Base @VER@ + PyST_GetScope@Base @VER@ + PySeqIter_New@Base @VER@ + PySeqIter_Type@Base @VER@ + PySequence_Check@Base @VER@ + PySequence_Concat@Base @VER@ + PySequence_Contains@Base @VER@ + PySequence_Count@Base @VER@ + PySequence_DelItem@Base @VER@ + PySequence_DelSlice@Base @VER@ + PySequence_Fast@Base @VER@ + PySequence_GetItem@Base @VER@ + PySequence_GetSlice@Base @VER@ + PySequence_In@Base @VER@ + PySequence_InPlaceConcat@Base @VER@ + PySequence_InPlaceRepeat@Base @VER@ + PySequence_Index@Base @VER@ + PySequence_Length@Base @VER@ + PySequence_List@Base @VER@ + PySequence_Repeat@Base @VER@ + PySequence_SetItem@Base @VER@ + PySequence_SetSlice@Base @VER@ + PySequence_Size@Base @VER@ + PySequence_Tuple@Base @VER@ + PySet_Add@Base @VER@ + PySet_Clear@Base @VER@ + PySet_Contains@Base @VER@ + PySet_Discard@Base @VER@ + PySet_Fini@Base @VER@ + PySet_New@Base @VER@ + PySet_Pop@Base @VER@ + PySet_Size@Base @VER@ + PySet_Type@Base @VER@ + PySignal_SetWakeupFd@Base @VER@ + PySlice_GetIndices@Base @VER@ + PySlice_GetIndicesEx@Base @VER@ + PySlice_New@Base @VER@ + PySlice_Type@Base @VER@ + PyStaticMethod_New@Base @VER@ + PyStaticMethod_Type@Base @VER@ + (optional)PyStringIO_Type@Base @VER@ + PyString_AsDecodedObject@Base @VER@ + PyString_AsDecodedString@Base @VER@ + PyString_AsEncodedObject@Base @VER@ + PyString_AsEncodedString@Base @VER@ + PyString_AsString@Base @VER@ + PyString_AsStringAndSize@Base @VER@ + PyString_Concat@Base @VER@ + PyString_ConcatAndDel@Base @VER@ + PyString_Decode@Base @VER@ + PyString_DecodeEscape@Base @VER@ + PyString_Encode@Base @VER@ + PyString_Fini@Base @VER@ + PyString_Format@Base @VER@ + PyString_FromFormat@Base @VER@ + PyString_FromFormatV@Base @VER@ + PyString_FromString@Base @VER@ + PyString_FromStringAndSize@Base @VER@ + PyString_InternFromString@Base @VER@ + PyString_InternImmortal@Base @VER@ + PyString_InternInPlace@Base @VER@ + PyString_Repr@Base @VER@ + PyString_Size@Base @VER@ + PyString_Type@Base @VER@ + PyStructSequence_InitType@Base @VER@ + PyStructSequence_New@Base @VER@ + PyStructSequence_UnnamedField@Base @VER@ + PySuper_Type@Base @VER@ + PySymtable_Build@Base @VER@ + PySymtable_Free@Base @VER@ + PySymtable_Lookup@Base @VER@ + PySys_AddWarnOption@Base @VER@ + PySys_GetFile@Base @VER@ + PySys_GetObject@Base @VER@ + PySys_HasWarnOptions@Base @VER@ + PySys_ResetWarnOptions@Base @VER@ + PySys_SetArgv@Base @VER@ + PySys_SetArgvEx@Base @VER@ + PySys_SetObject@Base @VER@ + PySys_SetPath@Base @VER@ + PySys_WriteStderr@Base @VER@ + PySys_WriteStdout@Base @VER@ + (optional)PyTextIOBase_Type@Base @VER@ + (optional)PyTextIOWrapper_Type@Base @VER@ + PyThreadState_Clear@Base @VER@ + PyThreadState_Delete@Base @VER@ + PyThreadState_DeleteCurrent@Base @VER@ + PyThreadState_Get@Base @VER@ + PyThreadState_GetDict@Base @VER@ + PyThreadState_New@Base @VER@ + PyThreadState_Next@Base @VER@ + PyThreadState_SetAsyncExc@Base @VER@ + PyThreadState_Swap@Base @VER@ + PyThread_ReInitTLS@Base @VER@ + PyThread_acquire_lock@Base @VER@ + PyThread_allocate_lock@Base @VER@ + PyThread_create_key@Base @VER@ + PyThread_delete_key@Base @VER@ + PyThread_delete_key_value@Base @VER@ + PyThread_exit_thread@Base @VER@ + PyThread_free_lock@Base @VER@ + PyThread_get_key_value@Base @VER@ + PyThread_get_stacksize@Base @VER@ + PyThread_get_thread_ident@Base @VER@ + PyThread_init_thread@Base @VER@ + PyThread_release_lock@Base @VER@ + PyThread_set_key_value@Base @VER@ + PyThread_set_stacksize@Base @VER@ + PyThread_start_new_thread@Base @VER@ + PyToken_OneChar@Base @VER@ + PyToken_ThreeChars@Base @VER@ + PyToken_TwoChars@Base @VER@ + PyTokenizer_Free@Base @VER@ + PyTokenizer_FromFile@Base @VER@ + PyTokenizer_FromString@Base @VER@ + PyTokenizer_Get@Base @VER@ + PyTokenizer_RestoreEncoding@Base @VER@ + PyTraceBack_Here@Base @VER@ + PyTraceBack_Print@Base @VER@ + PyTraceBack_Type@Base @VER@ + PyTupleIter_Type@Base @VER@ + PyTuple_ClearFreeList@Base @VER@ + PyTuple_Fini@Base @VER@ + PyTuple_GetItem@Base @VER@ + PyTuple_GetSlice@Base @VER@ + PyTuple_New@Base @VER@ + PyTuple_Pack@Base @VER@ + PyTuple_SetItem@Base @VER@ + PyTuple_Size@Base @VER@ + PyTuple_Type@Base @VER@ + PyType_ClearCache@Base @VER@ + PyType_GenericAlloc@Base @VER@ + PyType_GenericNew@Base @VER@ + PyType_IsSubtype@Base @VER@ + PyType_Modified@Base @VER@ + PyType_Ready@Base @VER@ + PyType_Type@Base @VER@ + PyUnicodeDecodeError_Create@Base @VER@ + PyUnicodeDecodeError_GetEncoding@Base @VER@ + PyUnicodeDecodeError_GetEnd@Base @VER@ + PyUnicodeDecodeError_GetObject@Base @VER@ + PyUnicodeDecodeError_GetReason@Base @VER@ + PyUnicodeDecodeError_GetStart@Base @VER@ + PyUnicodeDecodeError_SetEnd@Base @VER@ + PyUnicodeDecodeError_SetReason@Base @VER@ + PyUnicodeDecodeError_SetStart@Base @VER@ + PyUnicodeEncodeError_Create@Base @VER@ + PyUnicodeEncodeError_GetEncoding@Base @VER@ + PyUnicodeEncodeError_GetEnd@Base @VER@ + PyUnicodeEncodeError_GetObject@Base @VER@ + PyUnicodeEncodeError_GetReason@Base @VER@ + PyUnicodeEncodeError_GetStart@Base @VER@ + PyUnicodeEncodeError_SetEnd@Base @VER@ + PyUnicodeEncodeError_SetReason@Base @VER@ + PyUnicodeEncodeError_SetStart@Base @VER@ + PyUnicodeTranslateError_Create@Base @VER@ + PyUnicodeTranslateError_GetEnd@Base @VER@ + PyUnicodeTranslateError_GetObject@Base @VER@ + PyUnicodeTranslateError_GetReason@Base @VER@ + PyUnicodeTranslateError_GetStart@Base @VER@ + PyUnicodeTranslateError_SetEnd@Base @VER@ + PyUnicodeTranslateError_SetReason@Base @VER@ + PyUnicodeTranslateError_SetStart@Base @VER@ + PyUnicodeUCS4_AsASCIIString@Base @VER@ + PyUnicodeUCS4_AsCharmapString@Base @VER@ + PyUnicodeUCS4_AsEncodedObject@Base @VER@ + PyUnicodeUCS4_AsEncodedString@Base @VER@ + PyUnicodeUCS4_AsLatin1String@Base @VER@ + PyUnicodeUCS4_AsRawUnicodeEscapeString@Base @VER@ + PyUnicodeUCS4_AsUTF16String@Base @VER@ + PyUnicodeUCS4_AsUTF32String@Base @VER@ + PyUnicodeUCS4_AsUTF8String@Base @VER@ + PyUnicodeUCS4_AsUnicode@Base @VER@ + PyUnicodeUCS4_AsUnicodeEscapeString@Base @VER@ + PyUnicodeUCS4_AsWideChar@Base @VER@ + PyUnicodeUCS4_ClearFreelist@Base @VER@ + PyUnicodeUCS4_Compare@Base @VER@ + PyUnicodeUCS4_Concat@Base @VER@ + PyUnicodeUCS4_Contains@Base @VER@ + PyUnicodeUCS4_Count@Base @VER@ + PyUnicodeUCS4_Decode@Base @VER@ + PyUnicodeUCS4_DecodeASCII@Base @VER@ + PyUnicodeUCS4_DecodeCharmap@Base @VER@ + PyUnicodeUCS4_DecodeLatin1@Base @VER@ + PyUnicodeUCS4_DecodeRawUnicodeEscape@Base @VER@ + PyUnicodeUCS4_DecodeUTF16@Base @VER@ + PyUnicodeUCS4_DecodeUTF16Stateful@Base @VER@ + PyUnicodeUCS4_DecodeUTF32@Base @VER@ + PyUnicodeUCS4_DecodeUTF32Stateful@Base @VER@ + PyUnicodeUCS4_DecodeUTF8@Base @VER@ + PyUnicodeUCS4_DecodeUTF8Stateful@Base @VER@ + PyUnicodeUCS4_DecodeUnicodeEscape@Base @VER@ + PyUnicodeUCS4_Encode@Base @VER@ + PyUnicodeUCS4_EncodeASCII@Base @VER@ + PyUnicodeUCS4_EncodeCharmap@Base @VER@ + PyUnicodeUCS4_EncodeDecimal@Base @VER@ + PyUnicodeUCS4_EncodeLatin1@Base @VER@ + PyUnicodeUCS4_EncodeRawUnicodeEscape@Base @VER@ + PyUnicodeUCS4_EncodeUTF16@Base @VER@ + PyUnicodeUCS4_EncodeUTF32@Base @VER@ + PyUnicodeUCS4_EncodeUTF8@Base @VER@ + PyUnicodeUCS4_EncodeUnicodeEscape@Base @VER@ + PyUnicodeUCS4_Find@Base @VER@ + PyUnicodeUCS4_Format@Base @VER@ + PyUnicodeUCS4_FromEncodedObject@Base @VER@ + PyUnicodeUCS4_FromFormat@Base @VER@ + PyUnicodeUCS4_FromFormatV@Base @VER@ + PyUnicodeUCS4_FromObject@Base @VER@ + PyUnicodeUCS4_FromOrdinal@Base @VER@ + PyUnicodeUCS4_FromString@Base @VER@ + PyUnicodeUCS4_FromStringAndSize@Base @VER@ + PyUnicodeUCS4_FromUnicode@Base @VER@ + PyUnicodeUCS4_FromWideChar@Base @VER@ + PyUnicodeUCS4_GetDefaultEncoding@Base @VER@ + PyUnicodeUCS4_GetMax@Base @VER@ + PyUnicodeUCS4_GetSize@Base @VER@ + PyUnicodeUCS4_Join@Base @VER@ + PyUnicodeUCS4_Partition@Base @VER@ + PyUnicodeUCS4_RPartition@Base @VER@ + PyUnicodeUCS4_RSplit@Base @VER@ + PyUnicodeUCS4_Replace@Base @VER@ + PyUnicodeUCS4_Resize@Base @VER@ + PyUnicodeUCS4_RichCompare@Base @VER@ + PyUnicodeUCS4_SetDefaultEncoding@Base @VER@ + PyUnicodeUCS4_Split@Base @VER@ + PyUnicodeUCS4_Splitlines@Base @VER@ + PyUnicodeUCS4_Tailmatch@Base @VER@ + PyUnicodeUCS4_Translate@Base @VER@ + PyUnicodeUCS4_TranslateCharmap@Base @VER@ + PyUnicode_AsDecodedObject@Base @VER@ + PyUnicode_BuildEncodingMap@Base @VER@ + PyUnicode_DecodeUTF7@Base @VER@ + PyUnicode_DecodeUTF7Stateful@Base @VER@ + PyUnicode_EncodeUTF7@Base @VER@ + PyUnicode_Type@Base @VER@ + PyWeakref_GetObject@Base @VER@ + PyWeakref_NewProxy@Base @VER@ + PyWeakref_NewRef@Base @VER@ + PyWrapperDescr_Type@Base @VER@ + PyWrapper_New@Base @VER@ + Py_AddPendingCall@Base @VER@ + Py_AtExit@Base @VER@ + Py_BuildValue@Base @VER@ + Py_BytesWarningFlag@Base @VER@ + Py_CompileString@Base @VER@ + Py_CompileStringFlags@Base @VER@ + Py_DebugFlag@Base @VER@ + Py_DecRef@Base @VER@ + Py_DivisionWarningFlag@Base @VER@ + Py_DontWriteBytecodeFlag@Base @VER@ + Py_EndInterpreter@Base @VER@ + Py_Exit@Base @VER@ + Py_FatalError@Base @VER@ + Py_FdIsInteractive@Base @VER@ + Py_FileSystemDefaultEncoding@Base @VER@ + Py_Finalize@Base @VER@ + Py_FindMethod@Base @VER@ + Py_FindMethodInChain@Base @VER@ + Py_FlushLine@Base @VER@ + Py_FrozenFlag@Base @VER@ + Py_FrozenMain@Base @VER@ + Py_GetArgcArgv@Base @VER@ + Py_GetBuildInfo@Base @VER@ + Py_GetCompiler@Base @VER@ + Py_GetCopyright@Base @VER@ + Py_GetExecPrefix@Base @VER@ + Py_GetPath@Base @VER@ + Py_GetPlatform@Base @VER@ + Py_GetPrefix@Base @VER@ + Py_GetProgramFullPath@Base @VER@ + Py_GetProgramName@Base @VER@ + Py_GetPythonHome@Base @VER@ + Py_GetRecursionLimit@Base @VER@ + Py_GetVersion@Base @VER@ + Py_HashRandomizationFlag@Base @VER@ + Py_IgnoreEnvironmentFlag@Base @VER@ + Py_IncRef@Base @VER@ + Py_Initialize@Base @VER@ + Py_InitializeEx@Base @VER@ + Py_InspectFlag@Base @VER@ + Py_InteractiveFlag@Base @VER@ + Py_IsInitialized@Base @VER@ + Py_Main@Base @VER@ + Py_MakePendingCalls@Base @VER@ + Py_NewInterpreter@Base @VER@ + Py_NoSiteFlag@Base @VER@ + Py_NoUserSiteDirectory@Base @VER@ + Py_OptimizeFlag@Base @VER@ + Py_Py3kWarningFlag@Base @VER@ + Py_ReprEnter@Base @VER@ + Py_ReprLeave@Base @VER@ + Py_SetProgramName@Base @VER@ + Py_SetPythonHome@Base @VER@ + Py_SetRecursionLimit@Base @VER@ + Py_SubversionRevision@Base @VER@ + Py_SubversionShortBranch@Base @VER@ + Py_SymtableString@Base @VER@ + Py_TabcheckFlag@Base @VER@ + Py_UnicodeFlag@Base @VER@ + Py_UniversalNewlineFgets@Base @VER@ + Py_UniversalNewlineFread@Base @VER@ + Py_UseClassExceptionsFlag@Base @VER@ + Py_VaBuildValue@Base @VER@ + Py_VerboseFlag@Base @VER@ + Py_meta_grammar@Base @VER@ + Py_pgen@Base @VER@ + _PyArg_NoKeywords@Base @VER@ + _PyArg_ParseTupleAndKeywords_SizeT@Base @VER@ + _PyArg_ParseTuple_SizeT@Base @VER@ + _PyArg_Parse_SizeT@Base @VER@ + _PyArg_VaParseTupleAndKeywords_SizeT@Base @VER@ + _PyArg_VaParse_SizeT@Base @VER@ + _PyBuiltin_Init@Base @VER@ + _PyByteArray_empty_string@Base @VER@ + _PyBytes_FormatAdvanced@Base @VER@ + _PyCode_CheckLineNumber@Base @VER@ + _PyCode_ConstantKey@Base 2.7.11 + _PyCodecInfo_GetIncrementalDecoder@Base @VER@ + _PyCodecInfo_GetIncrementalEncoder@Base @VER@ + _PyCodec_DecodeText@Base @VER@ + _PyCodec_EncodeText@Base @VER@ + _PyCodec_Lookup@Base @VER@ + _PyCodec_LookupTextEncoding@Base @VER@ + _PyComplex_FormatAdvanced@Base @VER@ + _PyDict_Contains@Base @VER@ + _PyDict_DelItemIf@Base @VER@ + _PyDict_GetItemWithError@Base 2.7.11 + _PyDict_MaybeUntrack@Base @VER@ + _PyDict_NewPresized@Base @VER@ + _PyDict_Next@Base @VER@ + _PyErr_BadInternalCall@Base @VER@ + _PyErr_ReplaceException@Base @VER@ + _PyEval_CallTracing@Base @VER@ + _PyEval_SliceIndex@Base @VER@ + _PyEval_SliceIndexNotNone@Base @VER@ + _PyExc_Fini@Base @VER@ + _PyExc_Init@Base @VER@ + (optional)_PyFileIO_closed@Base @VER@ + _PyFile_SanitizeMode@Base @VER@ + _PyFloat_FormatAdvanced@Base @VER@ + _PyFloat_Init@Base @VER@ + _PyFloat_Pack4@Base @VER@ + _PyFloat_Pack8@Base @VER@ + _PyFloat_Unpack4@Base @VER@ + _PyFloat_Unpack8@Base @VER@ + _PyFrame_Init@Base @VER@ + _PyGC_Dump@Base @VER@ + _PyGC_generation0@Base @VER@ + _PyGILState_Fini@Base @VER@ + _PyGILState_Init@Base @VER@ + (optional)_PyIOBase_check_closed@Base @VER@ + (optional)_PyIOBase_check_readable@Base @VER@ + (optional)_PyIOBase_check_seekable@Base @VER@ + (optional)_PyIOBase_check_writable@Base @VER@ + (optional)_PyIOBase_finalize@Base @VER@ + (optional)_PyIO_ConvertSsize_t@Base @VER@ + (optional)_PyIO_empty_bytes@Base @VER@ + (optional)_PyIO_empty_str@Base @VER@ + (optional)_PyIO_find_line_ending@Base @VER@ + (optional)_PyIO_locale_module@Base @VER@ + (optional)_PyIO_os_module@Base @VER@ + (optional)_PyIO_str_close@Base @VER@ + (optional)_PyIO_str_closed@Base @VER@ + (optional)_PyIO_str_decode@Base @VER@ + (optional)_PyIO_str_encode@Base @VER@ + (optional)_PyIO_str_fileno@Base @VER@ + (optional)_PyIO_str_flush@Base @VER@ + (optional)_PyIO_str_getstate@Base @VER@ + (optional)_PyIO_str_isatty@Base @VER@ + (optional)_PyIO_str_newlines@Base @VER@ + (optional)_PyIO_str_nl@Base @VER@ + (optional)_PyIO_str_read1@Base @VER@ + (optional)_PyIO_str_read@Base @VER@ + (optional)_PyIO_str_readable@Base @VER@ + (optional)_PyIO_str_readinto@Base @VER@ + (optional)_PyIO_str_readline@Base @VER@ + (optional)_PyIO_str_reset@Base @VER@ + (optional)_PyIO_str_seek@Base @VER@ + (optional)_PyIO_str_seekable@Base @VER@ + (optional)_PyIO_str_setstate@Base @VER@ + (optional)_PyIO_str_tell@Base @VER@ + (optional)_PyIO_str_truncate@Base @VER@ + (optional)_PyIO_str_writable@Base @VER@ + (optional)_PyIO_str_write@Base @VER@ + (optional)_PyIO_trap_eintr@Base @VER@ + (optional)_PyIO_unsupported_operation@Base @VER@ + (optional)_PyIO_zero@Base @VER@ + _PyImportHooks_Init@Base @VER@ + _PyImport_AcquireLock@Base @VER@ + _PyImport_DynLoadFiletab@Base @VER@ + _PyImport_Filetab@Base @VER@ + _PyImport_FindExtension@Base @VER@ + _PyImport_FindModule@Base @VER@ + _PyImport_Fini@Base @VER@ + _PyImport_FixupExtension@Base @VER@ + _PyImport_GetDynLoadFunc@Base @VER@ + _PyImport_Init@Base @VER@ + _PyImport_Inittab@Base @VER@ + _PyImport_IsScript@Base @VER@ + _PyImport_LoadDynamicModule@Base @VER@ + _PyImport_ReleaseLock@Base @VER@ + _PyImport_ReInitLock@Base @VER@ + (optional)_PyIncrementalNewlineDecoder_decode@Base @VER@ + _PyInstance_Lookup@Base @VER@ + _PyInt_AsInt@Base @VER@ + _PyInt_Format@Base @VER@ + _PyInt_FormatAdvanced@Base @VER@ + _PyInt_FromGid@Base @VER@ + _PyInt_FromUid@Base @VER@ + _PyInt_Init@Base @VER@ + _PyList_Extend@Base @VER@ + _PyLong_AsByteArray@Base @VER@ + _PyLong_AsInt@Base @VER@ + _PyLong_Copy@Base @VER@ + _PyLong_DigitValue@Base @VER@ + _PyLong_Format@Base @VER@ + _PyLong_FormatAdvanced@Base @VER@ + _PyLong_Frexp@Base @VER@ + _PyLong_FromByteArray@Base @VER@ + _PyLong_Init@Base @VER@ + _PyLong_New@Base @VER@ + _PyLong_NumBits@Base @VER@ + _PyLong_Sign@Base @VER@ + _PyModule_Clear@Base @VER@ + _PyNode_SizeOf@Base @VER@ + _PyNumber_ConvertIntegralToInt@Base @VER@ + _PyOS_GetOpt@Base @VER@ + _PyOS_ReadlineTState@Base @VER@ + _PyOS_ResetGetOpt@Base @VER@ + _PyOS_URandom@Base @VER@ + _PyOS_ascii_formatd@Base @VER@ + _PyOS_ascii_strtod@Base @VER@ + _PyOS_mystrnicmp_hack@Base @VER@ + _PyOS_optarg@Base @VER@ + _PyOS_opterr@Base @VER@ + _PyOS_optind@Base @VER@ + _PyObject_CallFunction_SizeT@Base @VER@ + _PyObject_CallMethod_SizeT@Base @VER@ + _PyObject_Del@Base @VER@ + _PyObject_Dump@Base @VER@ + _PyObject_GC_Del@Base @VER@ + _PyObject_GC_Malloc@Base @VER@ + _PyObject_GC_New@Base @VER@ + _PyObject_GC_NewVar@Base @VER@ + _PyObject_GC_Resize@Base @VER@ + _PyObject_GC_Track@Base @VER@ + _PyObject_GC_UnTrack@Base @VER@ + _PyObject_GenericGetAttrWithDict@Base @VER@ + _PyObject_GenericSetAttrWithDict@Base @VER@ + _PyObject_GetDictPtr@Base @VER@ + _PyObject_LengthHint@Base @VER@ + _PyObject_LookupSpecial@Base @VER@ + _PyObject_New@Base @VER@ + _PyObject_NewVar@Base @VER@ + _PyObject_NextNotImplemented@Base @VER@ + _PyObject_RealIsInstance@Base @VER@ + _PyObject_RealIsSubclass@Base @VER@ + _PyObject_SlotCompare@Base @VER@ + _PyObject_Str@Base @VER@ + _PyParser_Grammar@Base @VER@ + _PyParser_TokenNames@Base @VER@ + _PyRandom_Fini@Base @VER@ + _PyRandom_Init@Base @VER@ + _PySequence_IterSearch@Base @VER@ + _PySet_Next@Base @VER@ + _PySet_NextEntry@Base @VER@ + _PySet_Update@Base @VER@ + _PySlice_AdjustIndices@Base @VER@ + _PySlice_Unpack@Base @VER@ + _PySlice_FromIndices@Base @VER@ + _PyString_Eq@Base @VER@ + _PyString_FormatLong@Base @VER@ + _PyString_InsertThousandsGrouping@Base @VER@ + _PyString_Join@Base @VER@ + _PyString_Resize@Base @VER@ + _PySys_GetSizeOf@Base @VER@ + _PySys_Init@Base @VER@ + _PyThreadState_Current@Base @VER@ + _PyThreadState_GetFrame@Base @VER@ + _PyThreadState_Init@Base @VER@ + _PyThreadState_Prealloc@Base @VER@ + _PyThread_CurrentFrames@Base @VER@ + _PyTime_DoubleToTimet@Base @VER@ + _PyTime_FloatTime@Base @VER@ + _PyTrash_delete_later@Base @VER@ + _PyTrash_delete_nesting@Base @VER@ + _PyTrash_deposit_object@Base @VER@ + _PyTrash_destroy_chain@Base @VER@ + _PyTrash_thread_deposit_object@Base @VER@ + _PyTrash_thread_destroy_chain@Base @VER@ + _PyTuple_MaybeUntrack@Base @VER@ + _PyTuple_Resize@Base @VER@ + _PyType_Lookup@Base @VER@ + _PyUnicodeUCS4_AsDefaultEncodedString@Base @VER@ + _PyUnicodeUCS4_Fini@Base @VER@ + _PyUnicodeUCS4_Init@Base @VER@ + _PyUnicodeUCS4_IsAlpha@Base @VER@ + _PyUnicodeUCS4_IsDecimalDigit@Base @VER@ + _PyUnicodeUCS4_IsDigit@Base @VER@ + _PyUnicodeUCS4_IsLinebreak@Base @VER@ + _PyUnicodeUCS4_IsLowercase@Base @VER@ + _PyUnicodeUCS4_IsNumeric@Base @VER@ + _PyUnicodeUCS4_IsTitlecase@Base @VER@ + _PyUnicodeUCS4_IsUppercase@Base @VER@ + _PyUnicodeUCS4_IsWhitespace@Base @VER@ + _PyUnicodeUCS4_ToDecimalDigit@Base @VER@ + _PyUnicodeUCS4_ToDigit@Base @VER@ + _PyUnicodeUCS4_ToLowercase@Base @VER@ + _PyUnicodeUCS4_ToNumeric@Base @VER@ + _PyUnicodeUCS4_ToTitlecase@Base @VER@ + _PyUnicodeUCS4_ToUppercase@Base @VER@ + _PyUnicode_BidirectionalNames@Base @VER@ + _PyUnicode_CategoryNames@Base @VER@ + _PyUnicode_Database_Records@Base @VER@ + _PyUnicode_DecodeUnicodeInternal@Base @VER@ + _PyUnicode_EastAsianWidthNames@Base @VER@ + _PyUnicode_FormatAdvanced@Base @VER@ + _PyUnicode_TypeRecords@Base @VER@ + _PyUnicode_XStrip@Base @VER@ + _PyWarnings_Init@Base @VER@ + _PyWeakref_CallableProxyType@Base @VER@ + _PyWeakref_ClearRef@Base @VER@ + _PyWeakref_GetWeakrefCount@Base @VER@ + _PyWeakref_ProxyType@Base @VER@ + _PyWeakref_RefType@Base @VER@ + _Py_Assert@Base @VER@ + _Py_Assign@Base @VER@ + _Py_Attribute@Base @VER@ + _Py_AugAssign@Base @VER@ + _Py_BinOp@Base @VER@ + _Py_BoolOp@Base @VER@ + _Py_Break@Base @VER@ + _Py_BuildValue_SizeT@Base @VER@ + _Py_Call@Base @VER@ + _Py_CheckInterval@Base @VER@ + _Py_CheckRecursionLimit@Base @VER@ + _Py_CheckRecursiveCall@Base @VER@ + _Py_ClassDef@Base @VER@ + _Py_Compare@Base @VER@ + _Py_Continue@Base @VER@ + _Py_Delete@Base @VER@ + _Py_Dict@Base @VER@ + _Py_DictComp@Base @VER@ + _Py_DisplaySourceLine@Base @VER@ + _Py_Ellipsis@Base @VER@ + _Py_EllipsisObject@Base @VER@ + _Py_ExceptHandler@Base @VER@ + _Py_Exec@Base @VER@ + _Py_Expr@Base @VER@ + _Py_Expression@Base @VER@ + _Py_ExtSlice@Base @VER@ + _Py_For@Base @VER@ + _Py_FunctionDef@Base @VER@ + _Py_GeneratorExp@Base @VER@ + _Py_Gid_Converter@Base @VER@ + _Py_Global@Base @VER@ + _Py_HashDouble@Base @VER@ + _Py_HashPointer@Base @VER@ + _Py_HashSecret@Base @VER@ + _Py_If@Base @VER@ + _Py_IfExp@Base @VER@ + _Py_Import@Base @VER@ + _Py_ImportFrom@Base @VER@ + _Py_Index@Base @VER@ + _Py_InsertThousandsGroupingLocale@Base @VER@ + _Py_Interactive@Base @VER@ + _Py_Lambda@Base @VER@ + _Py_List@Base @VER@ + _Py_ListComp@Base @VER@ + _Py_Mangle@Base @VER@ + _Py_Module@Base @VER@ + _Py_Name@Base @VER@ + _Py_NoneStruct@Base @VER@ + _Py_NotImplementedStruct@Base @VER@ + _Py_Num@Base @VER@ + _Py_PackageContext@Base @VER@ + _Py_Pass@Base @VER@ + _Py_Print@Base @VER@ + _Py_QnewFlag@Base @VER@ + _Py_Raise@Base @VER@ + _Py_ReadyTypes@Base @VER@ + _Py_ReleaseInternedStrings@Base @VER@ + _Py_Repr@Base @VER@ + _Py_Return@Base @VER@ + _Py_Set@Base @VER@ + _Py_SetComp@Base @VER@ + _Py_Slice@Base @VER@ + _Py_Str@Base @VER@ + _Py_Subscript@Base @VER@ + _Py_Suite@Base @VER@ + _Py_SwappedOp@Base @VER@ + _Py_Ticker@Base @VER@ + _Py_TrueStruct@Base @VER@ + _Py_TryExcept@Base @VER@ + _Py_TryFinally@Base @VER@ + _Py_Tuple@Base @VER@ + _Py_Uid_Converter@Base @VER@ + _Py_UnaryOp@Base @VER@ + _Py_VaBuildValue_SizeT@Base @VER@ + _Py_While@Base @VER@ + _Py_With@Base @VER@ + _Py_Yield@Base @VER@ + _Py_ZeroStruct@Base @VER@ + _Py_abstract_hack@Base @VER@ + _Py_add_one_to_index_C@Base @VER@ + _Py_add_one_to_index_F@Base @VER@ + (optional)_Py_acosh@Base @VER@ + _Py_addarc@Base @VER@ + _Py_addbit@Base @VER@ + _Py_adddfa@Base @VER@ + _Py_addfirstsets@Base @VER@ + _Py_addlabel@Base @VER@ + _Py_addstate@Base @VER@ + _Py_alias@Base @VER@ + _Py_arguments@Base @VER@ + _Py_ascii_whitespace@Base @VER@ + (optional)_Py_asinh@Base @VER@ + (optional)_Py_atanh@Base @VER@ + _Py_bytes_capitalize@Base @VER@ + _Py_bytes_isalnum@Base @VER@ + _Py_bytes_isalpha@Base @VER@ + _Py_bytes_isdigit@Base @VER@ + _Py_bytes_islower@Base @VER@ + _Py_bytes_isspace@Base @VER@ + _Py_bytes_istitle@Base @VER@ + _Py_bytes_isupper@Base @VER@ + _Py_bytes_lower@Base @VER@ + _Py_bytes_swapcase@Base @VER@ + _Py_bytes_title@Base @VER@ + _Py_bytes_upper@Base @VER@ + _Py_c_abs@Base @VER@ + _Py_c_diff@Base @VER@ + _Py_c_neg@Base @VER@ + _Py_c_pow@Base @VER@ + _Py_c_prod@Base @VER@ + _Py_c_quot@Base @VER@ + _Py_c_sum@Base @VER@ + _Py_capitalize__doc__@Base @VER@ + _Py_capsule_hack@Base @VER@ + _Py_cobject_hack@Base @VER@ + _Py_comprehension@Base @VER@ + _Py_ctype_table@Base @VER@ + _Py_ctype_tolower@Base @VER@ + _Py_ctype_toupper@Base @VER@ + _Py_delbitset@Base @VER@ + (arch=!m68k)_Py_dg_dtoa@Base @VER@ + (arch=!m68k)_Py_dg_freedtoa@Base @VER@ + (arch=!m68k)_Py_dg_strtod@Base @VER@ + _Py_double_round@Base @VER@ + (optional)_Py_expm1@Base @VER@ + _Py_findlabel@Base @VER@ + (arch=i386 lpia m68k)_Py_force_double@Base @VER@ + (arch=amd64 i386 lpia)_Py_get_387controlword@Base @VER@ + _Py_gitidentifier@Base 2.7.1 + _Py_gitversion@Base 2.7.1 + _Py_isalnum__doc__@Base @VER@ + _Py_isalpha__doc__@Base @VER@ + _Py_isdigit__doc__@Base @VER@ + _Py_islower__doc__@Base @VER@ + _Py_isspace__doc__@Base @VER@ + _Py_istitle__doc__@Base @VER@ + _Py_isupper__doc__@Base @VER@ + _Py_keyword@Base @VER@ + (optional)_Py_log1p@Base @VER@ + _Py_lower__doc__@Base @VER@ + _Py_mergebitset@Base @VER@ + _Py_meta_grammar@Base @VER@ + _Py_newbitset@Base @VER@ + _Py_newgrammar@Base @VER@ + (optional)_Py_parse_inf_or_nan@Base @VER@ + _Py_pgen@Base @VER@ + _Py_samebitset@Base @VER@ + (arch=amd64 i386 lpia)_Py_set_387controlword@Base @VER@ + _Py_swapcase__doc__@Base @VER@ + _Py_title__doc__@Base @VER@ + _Py_translatelabels@Base @VER@ + _Py_upper__doc__@Base @VER@ + + (optional)PyFPE_counter@Base @VER@ + (optional)PyFPE_dummy@Base @VER@ + (optional)PyFPE_jbuf@Base @VER@ + + asdl_int_seq_new@Base @VER@ + asdl_seq_new@Base @VER@ + +# don't check for the following symbols, found in extensions +# which either can be built as builtin or extension. + + (optional)fast_save_leave@Base @VER@ + (optional)partial_reduce@Base @VER@ + (optional)partial_setstate@Base @VER@ + + (optional)_Py_md5_append@Base @VER@ + (optional)_Py_md5_finish@Base @VER@ + (optional)_Py_md5_init@Base @VER@ + +# _check_for_multiple_distdirs@Base @VER@ + (optional)init_ast@Base @VER@ + (optional)init_bisect@Base @VER@ + (optional)init_codecs@Base @VER@ + (optional)init_collections@Base @VER@ + (optional)init_functools@Base @VER@ + (optional)init_hashlib@Base @VER@ + (optional)init_heapq@Base @VER@ + (optional)init_io@Base @VER@ + (optional)init_locale@Base @VER@ + (optional)init_md5@Base @VER@ + (optional)init_random@Base @VER@ + (optional)init_sha@Base @VER@ + (optional)init_sha256@Base @VER@ + (optional)init_sha512@Base @VER@ + (optional)init_socket@Base @VER@ + (optional)init_sockobject@Base @VER@ + (optional)init_sre@Base @VER@ + (optional)init_ssl@Base @VER@ + (optional)init_struct@Base @VER@ + (optional)init_symtable@Base @VER@ + (optional)init_weakref@Base @VER@ + (optional)initarray@Base @VER@ + (optional)initbinascii@Base @VER@ + (optional)initcPickle@Base @VER@ + (optional)initcStringIO@Base @VER@ + (optional)initcmath@Base @VER@ + (optional)initdatetime@Base @VER@ + (optional)initerrno@Base @VER@ + (optional)initfcntl@Base @VER@ + (optional)initgc@Base @VER@ + (optional)initgrp@Base @VER@ + (optional)initimp@Base @VER@ + (optional)inititertools@Base @VER@ + (optional)initmath@Base @VER@ + (optional)initoperator@Base @VER@ + (optional)initposix@Base @VER@ + (optional)initpwd@Base @VER@ + (optional)initselect@Base @VER@ + (optional)initsignal@Base @VER@ + (optional)initspwd@Base @VER@ + (optional)initstrop@Base @VER@ + (optional)initsyslog@Base @VER@ + (optional)initthread@Base @VER@ + (optional)inittime@Base @VER@ + (optional)initunicodedata@Base @VER@ + (optional)initxxsubtype@Base @VER@ + (optional)initzipimport@Base @VER@ + (optional)initzlib@Base @VER@ --- python2.7-2.7.15.orig/debian/locale-gen +++ python2.7-2.7.15/debian/locale-gen @@ -0,0 +1,31 @@ +#!/bin/sh + +LOCPATH=`pwd`/locales +export LOCPATH + +[ -d $LOCPATH ] || mkdir -p $LOCPATH + +umask 022 + +echo "Generating locales..." +while read locale charset; do + case $locale in \#*) continue;; esac + [ -n "$locale" -a -n "$charset" ] || continue + echo -n " `echo $locale | sed 's/\([^.\@]*\).*/\1/'`" + echo -n ".$charset" + echo -n `echo $locale | sed 's/\([^\@]*\)\(\@.*\)*/\2/'` + echo -n '...' + if [ -f $LOCPATH/$locale ]; then + input=$locale + else + input=`echo $locale | sed 's/\([^.]*\)[^@]*\(.*\)/\1\2/'` + fi + localedef -i $input -c -f $charset $LOCPATH/$locale #-A /etc/locale.alias + echo ' done'; \ +done < +# elif defined(__x86_64__) && defined(__ILP32__) +# include +# elif defined(__i386__) +# include +# elif defined(__aarch64__) && defined(__AARCH64EL__) +# if defined(__ILP32__) +# include +# else +# include +# endif +# elif defined(__aarch64__) && defined(__AARCH64EB__) +# if defined(__ILP32__) +# include +# else +# include +# endif +# elif defined(__alpha__) +# include +# elif defined(__ARM_EABI__) && defined(__ARM_PCS_VFP) +# if defined(__ARMEL__) +# include +# else +# include +# endif +# elif defined(__ARM_EABI__) && !defined(__ARM_PCS_VFP) +# if defined(__ARMEL__) +# include +# else +# include +# endif +# elif defined(__hppa__) +# include +# elif defined(__ia64__) +# include +# elif defined(__m68k__) && !defined(__mcoldfire__) +# include +# elif defined(__mips_hard_float) && defined(__mips_isa_rev) && (__mips_isa_rev >=6) && defined(_MIPSEL) +# if _MIPS_SIM == _ABIO32 +# include +# elif _MIPS_SIM == _ABIN32 +# include +# elif _MIPS_SIM == _ABI64 +# include +# else +# error unknown multiarch location for @header@ +# endif +# elif defined(__mips_hard_float) && defined(__mips_isa_rev) && (__mips_isa_rev >=6) +# if _MIPS_SIM == _ABIO32 +# include +# elif _MIPS_SIM == _ABIN32 +# include +# elif _MIPS_SIM == _ABI64 +# include +# else +# error unknown multiarch location for @header@ +# endif +# elif defined(__mips_hard_float) && defined(_MIPSEL) +# if _MIPS_SIM == _ABIO32 +# include +# elif _MIPS_SIM == _ABIN32 +# include +# elif _MIPS_SIM == _ABI64 +# include +# else +# error unknown multiarch location for @header@ +# endif +# elif defined(__mips_hard_float) +# if _MIPS_SIM == _ABIO32 +# include +# elif _MIPS_SIM == _ABIN32 +# include +# elif _MIPS_SIM == _ABI64 +# include +# else +# error unknown multiarch location for @header@ +# endif +# elif defined(__or1k__) +# include +# elif defined(__powerpc__) && defined(__SPE__) +# include +# elif defined(__powerpc64__) +# if defined(__LITTLE_ENDIAN__) +# include +# else +# include +# endif +# elif defined(__powerpc__) +# include +# elif defined(__s390x__) +# include +# elif defined(__s390__) +# include +# elif defined(__sh__) && defined(__LITTLE_ENDIAN__) +# include +# elif defined(__sparc__) && defined(__arch64__) +# include +# elif defined(__sparc__) +# include +# elif defined(__riscv) +# if __riscv_xlen == 64 +# include +# else +# include +# endif +# else +# error unknown multiarch location for @header@ +# endif +#elif defined(__FreeBSD_kernel__) +# if defined(__LP64__) +# include +# elif defined(__i386__) +# include +# else +# error unknown multiarch location for @header@ +# endif +#elif defined(__gnu_hurd__) +# include +#else +# error unknown multiarch location for @header@ +#endif --- python2.7-2.7.15.orig/debian/patches/add-python-config-sh.diff +++ python2.7-2.7.15/debian/patches/add-python-config-sh.diff @@ -0,0 +1,182 @@ +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -1190,6 +1190,8 @@ python-config: $(srcdir)/Misc/python-con + # Substitution happens here, as the completely-expanded BINDIR + # is not available in configure + sed -e "s,@EXENAME@,$(BINDIR)/python$(VERSION)$(EXE)," < $(srcdir)/Misc/python-config.in >python-config ++ # Replace makefile compat. variable references with shell script compat. ones; $(VAR) -> ${VAR} ++ sed -e "s,\$$(\([A-Za-z0-9_]*\)),\$$\{\1\},g" < Misc/python-config.sh >python-config.sh + + # Install the include files + INCLDIRSTOMAKE=$(INCLUDEDIR) $(CONFINCLUDEDIR) $(INCLUDEPY) $(CONFINCLUDEPY) +@@ -1249,6 +1251,7 @@ libainstall: @DEF_MAKE_RULE@ python-conf + $(INSTALL_SCRIPT) $(srcdir)/install-sh $(DESTDIR)$(LIBPL)/install-sh + $(INSTALL_SCRIPT) python-config $(DESTDIR)$(BINDIR)/python$(VERSION)-config + rm python-config ++ $(INSTALL_SCRIPT) python-config.sh $(DESTDIR)$(BINDIR)/python-config.sh + @if [ -s Modules/python.exp -a \ + "`echo $(MACHDEP) | sed 's/^\(...\).*/\1/'`" = "aix" ]; then \ + echo; echo "Installing support files for building shared extension modules on AIX:"; \ +Index: b/Misc/python-config.in +=================================================================== +--- a/Misc/python-config.in ++++ b/Misc/python-config.in +@@ -56,3 +56,11 @@ for opt in opt_flags: + libs.extend(getvar('LINKFORSHARED').split()) + print ' '.join(libs) + ++ elif opt == '--extension-suffix': ++ print sysconfig.get_config_var('SO') ++ ++ elif opt == '--abiflags': ++ print '' ++ ++ elif opt == '--configdir': ++ print sysconfig.get_config_var('LIBPL') +Index: b/Misc/python-config.sh.in +=================================================================== +--- /dev/null ++++ b/Misc/python-config.sh.in +@@ -0,0 +1,103 @@ ++#!/bin/sh ++ ++exit_with_usage () ++{ ++ echo "Usage: $0 --prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--extension-suffix|--help|--configdir" ++ exit $1 ++} ++ ++if [ "$1" = "" ] ; then ++ exit_with_usage 1 ++fi ++ ++# Returns the actual prefix where this script was installed to. ++installed_prefix () ++{ ++ local RESULT=$(dirname $(cd $(dirname "$1") && pwd -P)) ++ if [ $(which readlink) ] ; then ++ RESULT=$(readlink -f "$RESULT") ++ fi ++ echo $RESULT ++} ++ ++prefix_build="@prefix@" ++prefix_real=$(installed_prefix "$0") ++ ++# Use sed to fix paths from their built to locations to their installed to locations. ++prefix=$(echo "$prefix_build" | sed "s#$prefix_build#$prefix_real#") ++exec_prefix_build="@exec_prefix@" ++exec_prefix=$(echo "$exec_prefix_build" | sed "s#$exec_prefix_build#$prefix_real#") ++includedir=$(echo "@includedir@" | sed "s#$prefix_build#$prefix_real#") ++libdir=$(echo "@libdir@" | sed "s#$prefix_build#$prefix_real#") ++CFLAGS=$(echo "@CFLAGS@" | sed "s#$prefix_build#$prefix_real#") ++VERSION="@VERSION@" ++LIBM="@LIBM@" ++LIBC="@LIBC@" ++SYSLIBS="$LIBM $LIBC" ++ABIFLAGS="@DEBUG_EXT@" ++MULTIARCH="@MULTIARCH@" ++LIBS="-lpython${VERSION}${ABIFLAGS} @LIBS@ $SYSLIBS" ++BASECFLAGS="@BASECFLAGS@" ++LDLIBRARY="@LDLIBRARY@" ++LINKFORSHARED="@LINKFORSHARED@" ++OPT="@OPT@" ++PY_ENABLE_SHARED="@PY_ENABLE_SHARED@" ++LIBDEST=${prefix}/lib/python${VERSION} ++LIBPL=${LIBDEST}/config-${MULTIARCH}${ABIFLAGS} ++SO="${ABIFLAGS}.so" ++PYTHONFRAMEWORK="@PYTHONFRAMEWORK@" ++INCDIR="-I$includedir/python${VERSION}${ABIFLAGS}" ++PLATINCDIR="-I$includedir/$MULTIARCH/python${VERSION}${ABIFLAGS}" ++ ++# Scan for --help or unknown argument. ++for ARG in $* ++do ++ case $ARG in ++ --help) ++ exit_with_usage 0 ++ ;; ++ --prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--extension-suffix|--configdir) ++ ;; ++ *) ++ exit_with_usage 1 ++ ;; ++ esac ++done ++ ++for ARG in $* ++do ++ case $ARG in ++ --prefix) ++ echo "$prefix" ++ ;; ++ --exec-prefix) ++ echo "$exec_prefix" ++ ;; ++ --includes) ++ echo "$INCDIR" "$PLATINCDIR" ++ ;; ++ --cflags) ++ echo "$INCDIR $PLATINCDIR $BASECFLAGS $CFLAGS $OPT" ++ ;; ++ --libs) ++ echo "$LIBS" ++ ;; ++ --ldflags) ++ LINKFORSHAREDUSED= ++ if [ -z "$PYTHONFRAMEWORK" ] ; then ++ LINKFORSHAREDUSED=$LINKFORSHARED ++ fi ++ LIBPLUSED= ++ if [ "$PY_ENABLE_SHARED" = "0" ] ; then ++ LIBPLUSED="-L$LIBPL" ++ fi ++ echo "$LIBPLUSED -L$libdir $LIBS $LINKFORSHAREDUSED" ++ ;; ++ --extension-suffix) ++ echo "$SO" ++ ;; ++ --configdir) ++ echo "$LIBPL" ++ ;; ++esac ++done +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -915,6 +915,7 @@ fi + + # Other platforms follow + if test $enable_shared = "yes"; then ++ PY_ENABLE_SHARED=1 + AC_DEFINE(Py_ENABLE_SHARED, 1, [Defined if Python is built as a shared library.]) + case $ac_sys_system in + BeOS*) +@@ -975,6 +976,7 @@ if test $enable_shared = "yes"; then + + esac + else # shared is disabled ++ PY_ENABLE_SHARED=0 + case $ac_sys_system in + CYGWIN*) + BLDLIBRARY='$(LIBRARY)' +@@ -982,6 +984,7 @@ else # shared is disabled + ;; + esac + fi ++AC_SUBST(PY_ENABLE_SHARED) + + if test "$cross_compiling" = yes; then + RUNSHARED= +@@ -4954,7 +4957,7 @@ AC_MSG_RESULT($ENSUREPIP) + AC_SUBST(ENSUREPIP) + + # generate output files +-AC_CONFIG_FILES(Makefile.pre Modules/Setup.config Misc/python.pc) ++AC_CONFIG_FILES(Makefile.pre Modules/Setup.config Misc/python.pc Misc/python-config.sh) + AC_CONFIG_FILES([Modules/ld_so_aix], [chmod +x Modules/ld_so_aix]) + AC_OUTPUT + --- python2.7-2.7.15.orig/debian/patches/atomic-pyc-rename.diff +++ python2.7-2.7.15/debian/patches/atomic-pyc-rename.diff @@ -0,0 +1,34 @@ +--- a/Lib/py_compile.py ++++ b/Lib/py_compile.py +@@ -120,13 +120,24 @@ + return + if cfile is None: + cfile = file + (__debug__ and 'c' or 'o') +- with open(cfile, 'wb') as fc: +- fc.write('\0\0\0\0') +- wr_long(fc, timestamp) +- marshal.dump(codeobject, fc) +- fc.flush() +- fc.seek(0, 0) +- fc.write(MAGIC) ++ # Atomically write the pyc/pyo file. Issue #13146. ++ # id() is used to generate a pseudo-random filename. ++ path_tmp = '{}.{}'.format(cfile, id(cfile)) ++ try: ++ with open(path_tmp, 'wb') as fc: ++ fc.write('\0\0\0\0') ++ wr_long(fc, timestamp) ++ marshal.dump(codeobject, fc) ++ fc.flush() ++ fc.seek(0, 0) ++ fc.write(MAGIC) ++ os.rename(path_tmp, cfile) ++ except OSError: ++ try: ++ os.unlink(path_tmp) ++ except OSError: ++ pass ++ raise + + def main(args=None): + """Compile several source files. --- python2.7-2.7.15.orig/debian/patches/bdist-wininst-notfound.diff +++ python2.7-2.7.15/debian/patches/bdist-wininst-notfound.diff @@ -0,0 +1,25 @@ +# DP: the wininst-* files cannot be built within Debian, needing a +# DP: zlib mingw build, which the zlib maintainer isn't going to provide. + +--- a/Lib/distutils/command/bdist_wininst.py ++++ b/Lib/distutils/command/bdist_wininst.py +@@ -14,6 +14,7 @@ + from distutils.core import Command + from distutils.dir_util import remove_tree + from distutils.errors import DistutilsOptionError, DistutilsPlatformError ++from distutils.errors import DistutilsFileError + from distutils import log + from distutils.util import get_platform + +@@ -360,7 +361,10 @@ + sfix = '' + + filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) +- f = open(filename, "rb") ++ try: ++ f = open(filename, "rb") ++ except IOError, msg: ++ raise DistutilsFileError, str(msg) + ', %s not included in the Debian packages.' % filename + try: + return f.read() + finally: --- python2.7-2.7.15.orig/debian/patches/bpo-33570.diff +++ python2.7-2.7.15/debian/patches/bpo-33570.diff @@ -0,0 +1,113 @@ +From 9e32244ea7d2621030f040b0f4e5af89480ecc0f Mon Sep 17 00:00:00 2001 +From: Christian Heimes +Date: Wed, 15 Aug 2018 09:07:28 +0200 +Subject: [PATCH] [2.7] bpo-33570: TLS 1.3 ciphers for OpenSSL 1.1.1 (GH-6976) + (GH-8760) + +Change TLS 1.3 cipher suite settings for compatibility with OpenSSL +1.1.1-pre6 and newer. OpenSSL 1.1.1 will have TLS 1.3 cipers enabled by +default. + +Also update multissltests to test with latest OpenSSL. + +Signed-off-by: Christian Heimes . +(cherry picked from commit 3e630c541b35c96bfe5619165255e559f577ee71) + +Co-authored-by: Christian Heimes +--- + Doc/library/ssl.rst | 8 ++-- + Lib/test/test_ssl.py | 37 +++++++++++-------- + .../2018-05-18-21-50-47.bpo-33570.7CZy4t.rst | 3 ++ + 3 files changed, 27 insertions(+), 21 deletions(-) + create mode 100644 Misc/NEWS.d/next/Library/2018-05-18-21-50-47.bpo-33570.7CZy4t.rst + +diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst +index 042103177230..7c7c85b833a8 100644 +--- a/Doc/library/ssl.rst ++++ b/Doc/library/ssl.rst +@@ -294,11 +294,6 @@ purposes. + + 3DES was dropped from the default cipher string. + +- .. versionchanged:: 2.7.15 +- +- TLS 1.3 cipher suites TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, +- and TLS_CHACHA20_POLY1305_SHA256 were added to the default cipher string. +- + .. function:: _https_verify_certificates(enable=True) + + Specifies whether or not server certificates are verified when creating +@@ -1179,6 +1174,9 @@ to speed up repeated connections from the same clients. + when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will + give the currently selected cipher. + ++ OpenSSL 1.1.1 has TLS 1.3 cipher suites enabled by default. The suites ++ cannot be disabled with :meth:`~SSLContext.set_ciphers`. ++ + .. method:: SSLContext.set_alpn_protocols(protocols) + + Specify which protocols the socket should advertise during the SSL/TLS +diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py +index 7d06dc57c8e1..2746a81ce080 100644 +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -2772,19 +2772,24 @@ def test_do_handshake_enotconn(self): + sock.do_handshake() + self.assertEqual(cm.exception.errno, errno.ENOTCONN) + +- def test_default_ciphers(self): +- context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) +- try: +- # Force a set of weak ciphers on our client context +- context.set_ciphers("DES") +- except ssl.SSLError: +- self.skipTest("no DES cipher available") +- with ThreadedEchoServer(CERTFILE, +- ssl_version=ssl.PROTOCOL_SSLv23, +- chatty=False) as server: +- with closing(context.wrap_socket(socket.socket())) as s: +- with self.assertRaises(ssl.SSLError): +- s.connect((HOST, server.port)) ++ def test_no_shared_ciphers(self): ++ server_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ++ server_context.load_cert_chain(SIGNED_CERTFILE) ++ client_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ++ client_context.verify_mode = ssl.CERT_REQUIRED ++ client_context.check_hostname = True ++ ++ # OpenSSL enables all TLS 1.3 ciphers, enforce TLS 1.2 for test ++ client_context.options |= ssl.OP_NO_TLSv1_3 ++ # Force different suites on client and master ++ client_context.set_ciphers("AES128") ++ server_context.set_ciphers("AES256") ++ with ThreadedEchoServer(context=server_context) as server: ++ s = client_context.wrap_socket( ++ socket.socket(), ++ server_hostname="localhost") ++ with self.assertRaises(ssl.SSLError): ++ s.connect((HOST, server.port)) + self.assertIn("no shared cipher", str(server.conn_errors[0])) + + def test_version_basic(self): +@@ -2815,9 +2820,9 @@ def test_tls1_3(self): + with context.wrap_socket(socket.socket()) as s: + s.connect((HOST, server.port)) + self.assertIn(s.cipher()[0], [ +- 'TLS13-AES-256-GCM-SHA384', +- 'TLS13-CHACHA20-POLY1305-SHA256', +- 'TLS13-AES-128-GCM-SHA256', ++ 'TLS_AES_256_GCM_SHA384', ++ 'TLS_CHACHA20_POLY1305_SHA256', ++ 'TLS_AES_128_GCM_SHA256', + ]) + + @unittest.skipUnless(ssl.HAS_ECDH, "test requires ECDH-enabled OpenSSL") +diff --git a/Misc/NEWS.d/next/Library/2018-05-18-21-50-47.bpo-33570.7CZy4t.rst b/Misc/NEWS.d/next/Library/2018-05-18-21-50-47.bpo-33570.7CZy4t.rst +new file mode 100644 +index 000000000000..bd719a47e8f8 +--- /dev/null ++++ b/Misc/NEWS.d/next/Library/2018-05-18-21-50-47.bpo-33570.7CZy4t.rst +@@ -0,0 +1,3 @@ ++Change TLS 1.3 cipher suite settings for compatibility with OpenSSL ++1.1.1-pre6 and newer. OpenSSL 1.1.1 will have TLS 1.3 cipers enabled by ++default. --- python2.7-2.7.15.orig/debian/patches/bpo-34818.diff +++ python2.7-2.7.15/debian/patches/bpo-34818.diff @@ -0,0 +1,29 @@ +From 41ff2b42613e2b21c71f8cc85c38b41044f41c29 Mon Sep 17 00:00:00 2001 +From: Dimitri John Ledkov +Date: Fri, 28 Sep 2018 14:15:52 +0100 +Subject: [PATCH] bpo-34818: Add missing closing() wrapper in test_tls1_3. + +Python 2.7 socket classes do not implement context manager protocol, +hence closing() is required around it. Resolves testcase error +traceback. + +Signed-off-by: Dimitri John Ledkov + +https://bugs.python.org/issue34818 +--- + Lib/test/test_ssl.py | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py +index dc14e22ad121..a5ba49b321ef 100644 +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -2812,7 +2812,7 @@ def test_tls1_3(self): + ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_TLSv1_2 + ) + with ThreadedEchoServer(context=context) as server: +- with context.wrap_socket(socket.socket()) as s: ++ with closing(context.wrap_socket(socket.socket())) as s: + s.connect((HOST, server.port)) + self.assertIn(s.cipher()[0], [ + 'TLS13-AES-256-GCM-SHA384', --- python2.7-2.7.15.orig/debian/patches/bpo-34834.diff +++ python2.7-2.7.15/debian/patches/bpo-34834.diff @@ -0,0 +1,29 @@ +From 4fa35e8b1ebb2a8e88ba7c4c9cd2a17b35638ee6 Mon Sep 17 00:00:00 2001 +From: Dimitri John Ledkov +Date: Fri, 28 Sep 2018 16:34:16 +0100 +Subject: [PATCH] bpo-34834: Fix test_ssl.test_options to account for + OP_ENABLE_MIDDLEBOX_COMPAT. + +Signed-off-by: Dimitri John Ledkov + +https://bugs.python.org/issue34834 +--- + Lib/test/test_ssl.py | 5 +++++ + 1 file changed, 5 insertions(+) + +diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py +index dc14e22ad121..03a76ee6aba2 100644 +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -777,6 +777,11 @@ def test_options(self): + default = (ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) + if not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0): + default |= ssl.OP_NO_COMPRESSION ++ if not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 1): ++ # define MIDDLEBOX constant, as python2.7 does not know about it ++ # but it is used by default. ++ OP_ENABLE_MIDDLEBOX_COMPAT = 1048576L ++ default |= OP_ENABLE_MIDDLEBOX_COMPAT + self.assertEqual(default, ctx.options) + ctx.options |= ssl.OP_NO_TLSv1 + self.assertEqual(default | ssl.OP_NO_TLSv1, ctx.options) --- python2.7-2.7.15.orig/debian/patches/bpo-34836.diff +++ python2.7-2.7.15/debian/patches/bpo-34836.diff @@ -0,0 +1,26 @@ +From 65e10ca6815f1471e49bf7ad34d6652f079d31c8 Mon Sep 17 00:00:00 2001 +From: Dimitri John Ledkov +Date: Fri, 28 Sep 2018 17:30:19 +0100 +Subject: [PATCH] bpo-34836: fix test_default_ecdh_curve, needs no tlsv1.3. + +Signed-off-by: Dimitri John Ledkov + +https://bugs.python.org/issue34836 +--- + Lib/test/test_ssl.py | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py +index dc14e22ad121..bc3be9d0b132 100644 +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -2826,6 +2826,9 @@ def test_default_ecdh_curve(self): + # should be enabled by default on SSL contexts. + context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + context.load_cert_chain(CERTFILE) ++ # TLSv1.3 defaults to PFS key agreement and no longer has KEA in ++ # cipher name. ++ context.options |= ssl.OP_NO_TLSv1_3 + # Prior to OpenSSL 1.0.0, ECDH ciphers have to be enabled + # explicitly using the 'ECCdraft' cipher alias. Otherwise, + # our default cipher list should prefer ECDH-based ciphers --- python2.7-2.7.15.orig/debian/patches/bsddb-libpath.diff +++ python2.7-2.7.15/debian/patches/bsddb-libpath.diff @@ -0,0 +1,21 @@ +# DP: Don't add the bsddb multilib path, if already in the standard lib path + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -1090,7 +1090,13 @@ class PyBuildExt(build_ext): + if db_setup_debug: + print "bsddb using BerkeleyDB lib:", db_ver, dblib + print "bsddb lib dir:", dblib_dir, " inc dir:", db_incdir +- db_incs = [db_incdir] ++ # only add db_incdir/dblib_dir if not in the standard paths ++ if db_incdir in inc_dirs: ++ db_incs = [] ++ else: ++ db_incs = [db_incdir] ++ if dblib_dir[0] in lib_dirs: ++ dblib_dir = [] + dblibs = [dblib] + # We add the runtime_library_dirs argument because the + # BerkeleyDB lib we're linking against often isn't in the --- python2.7-2.7.15.orig/debian/patches/build-hash.diff +++ python2.7-2.7.15/debian/patches/build-hash.diff @@ -0,0 +1,24 @@ +# DP: Always build the _md5, _sha1, _sha256 and _sha512 extension modules. + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -874,7 +874,7 @@ class PyBuildExt(build_ext): + print ("warning: openssl 0x%08x is too old for _hashlib" % + openssl_ver) + missing.append('_hashlib') +- if COMPILED_WITH_PYDEBUG or not have_usable_openssl: ++ if True or COMPILED_WITH_PYDEBUG or not have_usable_openssl: + # The _sha module implements the SHA1 hash algorithm. + exts.append( Extension('_sha', ['shamodule.c']) ) + # The _md5 module implements the RSA Data Security, Inc. MD5 +@@ -885,7 +885,7 @@ class PyBuildExt(build_ext): + depends = ['md5.h']) ) + + min_sha2_openssl_ver = 0x00908000 +- if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver: ++ if True or COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver: + # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash + exts.append( Extension('_sha256', ['sha256module.c']) ) + exts.append( Extension('_sha512', ['sha512module.c']) ) --- python2.7-2.7.15.orig/debian/patches/build-libpython.diff +++ python2.7-2.7.15/debian/patches/build-libpython.diff @@ -0,0 +1,24 @@ +# DP: Don't include object files twice in libpython. + +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -400,7 +400,7 @@ LIBRARY_OBJS= \ + $(PYTHON_OBJS) \ + $(MODULE_OBJS) \ + $(SIGNAL_OBJS) \ +- $(MODOBJS) ++ $(sort $(MODOBJS)) + + ######################################################################### + # Rules +@@ -542,7 +542,7 @@ $(LIBRARY): $(LIBRARY_OBJS) + $(AR) $(ARFLAGS) $@ $(OBJECT_OBJS) + $(AR) $(ARFLAGS) $@ $(PYTHON_OBJS) + $(AR) $(ARFLAGS) $@ $(MODULE_OBJS) $(SIGNAL_OBJS) +- $(AR) $(ARFLAGS) $@ $(MODOBJS) ++ $(AR) $(ARFLAGS) $@ $(sort $(MODOBJS)) + $(RANLIB) $@ + + libpython$(VERSION).so: $(LIBRARY_OBJS) --- python2.7-2.7.15.orig/debian/patches/cthreads.diff +++ python2.7-2.7.15/debian/patches/cthreads.diff @@ -0,0 +1,39 @@ +# DP: Remove cthreads detection + +--- a/configure.ac ++++ b/configure.ac +@@ -2154,7 +2154,6 @@ + + # Templates for things AC_DEFINEd more than once. + # For a single AC_DEFINE, no template is needed. +-AH_TEMPLATE(C_THREADS,[Define if you have the Mach cthreads package]) + AH_TEMPLATE(_REENTRANT, + [Define to force use of thread-safe errno, h_errno, and other functions]) + AH_TEMPLATE(WITH_THREAD, +@@ -2236,17 +2235,6 @@ + AC_MSG_RESULT($unistd_defines_pthreads) + + AC_DEFINE(_REENTRANT) +- AC_CHECK_HEADER(cthreads.h, [AC_DEFINE(WITH_THREAD) +- AC_DEFINE(C_THREADS) +- AC_DEFINE(HURD_C_THREADS, 1, +- [Define if you are using Mach cthreads directly under /include]) +- LIBS="$LIBS -lthreads" +- THREADOBJ="Python/thread.o"],[ +- AC_CHECK_HEADER(mach/cthreads.h, [AC_DEFINE(WITH_THREAD) +- AC_DEFINE(C_THREADS) +- AC_DEFINE(MACH_C_THREADS, 1, +- [Define if you are using Mach cthreads under mach /]) +- THREADOBJ="Python/thread.o"],[ + AC_MSG_CHECKING(for --with-pth) + AC_ARG_WITH([pth], + AS_HELP_STRING([--with-pth], [use GNU pth threading libraries]), +@@ -2301,7 +2289,7 @@ + LIBS="$LIBS -lcma" + THREADOBJ="Python/thread.o"],[ + USE_THREAD_MODULE="#"]) +- ])])])])])])])])])]) ++ ])])])])])])])]) + + AC_CHECK_LIB(mpc, usconfig, [AC_DEFINE(WITH_THREAD) + LIBS="$LIBS -lmpc" --- python2.7-2.7.15.orig/debian/patches/ctypes-arm.diff +++ python2.7-2.7.15/debian/patches/ctypes-arm.diff @@ -0,0 +1,34 @@ +Index: b/Lib/ctypes/util.py +=================================================================== +--- a/Lib/ctypes/util.py ++++ b/Lib/ctypes/util.py +@@ -236,16 +236,27 @@ elif os.name == "posix": + + def _findSoname_ldconfig(name): + import struct ++ # XXX this code assumes that we know all unames and that a single ++ # ABI is supported per uname; instead we should find what the ++ # ABI is (e.g. check ABI of current process) or simply ask libc ++ # to load the library for us ++ uname = os.uname()[4] ++ # ARM has a variety of unames, e.g. armv7l ++ if uname.startswith("arm"): ++ uname = "arm" + if struct.calcsize('l') == 4: +- machine = os.uname()[4] + '-32' ++ machine = uname + '-32' + else: +- machine = os.uname()[4] + '-64' ++ machine = uname + '-64' + mach_map = { + 'x86_64-64': 'libc6,x86-64', + 'ppc64-64': 'libc6,64bit', + 'sparc64-64': 'libc6,64bit', + 's390x-64': 'libc6,64bit', + 'ia64-64': 'libc6,IA-64', ++ # this actually breaks on biarch or multiarch as the first ++ # library wins; uname doesn't tell us which ABI we're using ++ 'arm-32': 'libc6(,hard-float)?', + } + abi_type = mach_map.get(machine, 'libc6') + --- python2.7-2.7.15.orig/debian/patches/deb-locations.diff +++ python2.7-2.7.15/debian/patches/deb-locations.diff @@ -0,0 +1,73 @@ +# DP: adjust locations of directories to debian policy + +Index: b/Demo/tkinter/guido/ManPage.py +=================================================================== +--- a/Demo/tkinter/guido/ManPage.py ++++ b/Demo/tkinter/guido/ManPage.py +@@ -189,8 +189,9 @@ ManPage = ReadonlyManPage + def test(): + import os + import sys +- # XXX This directory may be different on your system +- MANDIR = '/usr/local/man/mann' ++ # XXX This directory may be different on your system, ++ # it is here set for Debian GNU/Linux. ++ MANDIR = '/usr/share/man' + DEFAULTPAGE = 'Tcl' + formatted = 0 + if sys.argv[1:] and sys.argv[1] == '-f': +Index: b/Demo/tkinter/guido/tkman.py +=================================================================== +--- a/Demo/tkinter/guido/tkman.py ++++ b/Demo/tkinter/guido/tkman.py +@@ -9,8 +9,8 @@ import re + from Tkinter import * + from ManPage import ManPage + +-MANNDIRLIST = ['/depot/sundry/man/mann','/usr/local/man/mann'] +-MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/local/man/man3'] ++MANNDIRLIST = ['/depot/sundry/man/mann','/usr/share/man/mann'] ++MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/share/man/man3'] + + foundmanndir = 0 + for dir in MANNDIRLIST: +Index: b/Misc/python.man +=================================================================== +--- a/Misc/python.man ++++ b/Misc/python.man +@@ -337,7 +337,7 @@ exception). Error messages are written + These are subject to difference depending on local installation + conventions; ${prefix} and ${exec_prefix} are installation-dependent + and should be interpreted as for GNU software; they may be the same. +-The default for both is \fI/usr/local\fP. ++On Debian GNU/{Hurd,Linux} the default for both is \fI/usr\fP. + .IP \fI${exec_prefix}/bin/python\fP + Recommended location of the interpreter. + .PP +Index: b/Tools/faqwiz/faqconf.py +=================================================================== +--- a/Tools/faqwiz/faqconf.py ++++ b/Tools/faqwiz/faqconf.py +@@ -21,7 +21,7 @@ OWNERNAME = "FAQ owner" + OWNEREMAIL = "nobody@anywhere.org" # Email for feedback + HOMEURL = "http://www.python.org" # Related home page + HOMENAME = "Python home" # Name of related home page +-RCSBINDIR = "/usr/local/bin/" # Directory containing RCS commands ++RCSBINDIR = "/usr/bin/" # Directory containing RCS commands + # (must end in a slash) + + # Parameters you can normally leave alone +Index: b/Tools/webchecker/webchecker.py +=================================================================== +--- a/Tools/webchecker/webchecker.py ++++ b/Tools/webchecker/webchecker.py +@@ -19,7 +19,8 @@ file index.html in that directory is ret + a directory listing is returned. Now, you can point webchecker to the + document tree in the local file system of your HTTP daemon, and have + most of it checked. In fact the default works this way if your local +-web tree is located at /usr/local/etc/httpd/htdpcs (the default for ++web tree is located at /var/www, which is the default for Debian ++GNU/Linux. Other systems use /usr/local/etc/httpd/htdocs (the default for + the NCSA HTTP daemon and probably others). + + Report printed: --- python2.7-2.7.15.orig/debian/patches/deb-setup.diff +++ python2.7-2.7.15/debian/patches/deb-setup.diff @@ -0,0 +1,21 @@ +# DP: Don't include /usr/local/include and /usr/local/lib as gcc search paths + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -454,10 +454,10 @@ class PyBuildExt(build_ext): + os.unlink(tmpfile) + + def detect_modules(self): +- # Ensure that /usr/local is always used +- if not cross_compiling: +- add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') +- add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') ++ # On Debian /usr/local is always used, so we don't include it twice ++ #if not cross_compiling: ++ # add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') ++ # add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') + if cross_compiling: + self.add_gcc_paths() + self.add_multiarch_paths() --- python2.7-2.7.15.orig/debian/patches/debug-build.diff +++ python2.7-2.7.15/debian/patches/debug-build.diff @@ -0,0 +1,248 @@ +# DP: Change the interpreter to build and install python extensions +# DP: built with the python-dbg interpreter with a different name into +# DP: the same path (by appending `_d' to the extension name). + +Index: b/Lib/distutils/command/build.py +=================================================================== +--- a/Lib/distutils/command/build.py ++++ b/Lib/distutils/command/build.py +@@ -91,7 +91,8 @@ class build(Command): + # 'lib.' under the base build directory. We only use one of + # them for a given distribution, though -- + if self.build_purelib is None: +- self.build_purelib = os.path.join(self.build_base, 'lib') ++ self.build_purelib = os.path.join(self.build_base, ++ 'lib' + plat_specifier) + if self.build_platlib is None: + self.build_platlib = os.path.join(self.build_base, + 'lib' + plat_specifier) +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -90,7 +90,7 @@ def get_python_inc(plat_specific=0, pref + # Include is located in the srcdir + inc_dir = os.path.join(srcdir, "Include") + return inc_dir +- return os.path.join(prefix, "include", "python" + get_python_version()) ++ return os.path.join(prefix, "include", "python" + get_python_version())+(sys.pydebug and "_d" or "") + elif os.name == "nt": + return os.path.join(prefix, "include") + elif os.name == "os2": +@@ -263,7 +263,7 @@ def get_makefile_filename(): + if python_build: + return os.path.join(project_base, "Makefile") + lib_dir = get_python_lib(plat_specific=1, standard_lib=1) +- return os.path.join(lib_dir, "config", "Makefile") ++ return os.path.join(lib_dir, "config"+(sys.pydebug and "_d" or ""), "Makefile") + + + def parse_config_h(fp, g=None): +Index: b/Lib/sysconfig.py +=================================================================== +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -338,7 +338,7 @@ def get_makefile_filename(): + """Return the path of the Makefile.""" + if _PYTHON_BUILD: + return os.path.join(_PROJECT_BASE, "Makefile") +- return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config", "Makefile") ++ return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config" + (sys.pydebug and "_d" or ""), "Makefile") + + # Issue #22199: retain undocumented private name for compatibility + _get_makefile_filename = get_makefile_filename +@@ -470,7 +470,7 @@ def get_config_h_filename(): + else: + inc_dir = _PROJECT_BASE + else: +- inc_dir = get_path('platinclude').replace("/usr/local","/usr",1) ++ inc_dir = get_path('platinclude').replace("/usr/local","/usr",1)+(sys.pydebug and "_d" or "") + return os.path.join(inc_dir, 'pyconfig.h') + + def get_scheme_names(): +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -121,8 +121,8 @@ SCRIPTDIR= $(prefix)/lib + # Detailed destination directories + BINLIBDEST= $(LIBDIR)/python$(VERSION) + LIBDEST= $(SCRIPTDIR)/python$(VERSION) +-INCLUDEPY= $(INCLUDEDIR)/python$(VERSION) +-CONFINCLUDEPY= $(CONFINCLUDEDIR)/python$(VERSION) ++INCLUDEPY= $(INCLUDEDIR)/python$(VERSION)$(DEBUG_EXT) ++CONFINCLUDEPY= $(CONFINCLUDEDIR)/python$(VERSION)$(DEBUG_EXT) + LIBP= $(LIBDIR)/python$(VERSION) + + # Symbols used for using shared libraries +@@ -136,6 +136,8 @@ DESTSHARED= $(BINLIBDEST)/lib-dynload + EXE= @EXEEXT@ + BUILDEXE= @BUILDEXEEXT@ + ++DEBUG_EXT= @DEBUG_EXT@ ++ + # Short name and location for Mac OS X Python framework + UNIVERSALSDK=@UNIVERSALSDK@ + PYTHONFRAMEWORK= @PYTHONFRAMEWORK@ +@@ -545,7 +547,7 @@ $(LIBRARY): $(LIBRARY_OBJS) + $(AR) $(ARFLAGS) $@ $(sort $(MODOBJS)) + $(RANLIB) $@ + +-libpython$(VERSION).so: $(LIBRARY_OBJS) ++libpython$(VERSION)$(DEBUG_EXT).so: $(LIBRARY_OBJS) + if test $(INSTSONAME) != $(LDLIBRARY); then \ + $(BLDSHARED) $(PY_LDFLAGS) $(CCSHARED) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LN) -f $(INSTSONAME) $@; \ +@@ -1201,8 +1203,8 @@ inclinstall: + $(INSTALL_DATA) pyconfig.h $(DESTDIR)$(CONFINCLUDEPY)/pyconfig.h + + # Install the library and miscellaneous stuff needed for extending/embedding +-# This goes into $(exec_prefix) +-LIBPL= $(LIBP)/config ++# This goes into $(exec_prefix)$(DEBUG_EXT) ++LIBPL= $(LIBP)/config$(DEBUG_EXT) + + # pkgconfig directory + LIBPC= $(LIBDIR)/pkgconfig +Index: b/Misc/python-config.in +=================================================================== +--- a/Misc/python-config.in ++++ b/Misc/python-config.in +@@ -44,7 +44,7 @@ for opt in opt_flags: + print ' '.join(flags) + + elif opt in ('--libs', '--ldflags'): +- libs = ['-lpython' + pyver] ++ libs = ['-lpython' + pyver + (sys.pydebug and "_d" or "")] + libs += getvar('LIBS').split() + libs += getvar('SYSLIBS').split() + # add the prefix/lib/pythonX.Y/config dir, but only if there is no +Index: b/Python/dynload_shlib.c +=================================================================== +--- a/Python/dynload_shlib.c ++++ b/Python/dynload_shlib.c +@@ -46,6 +46,10 @@ const struct filedescr _PyImport_DynLoad + {"module.exe", "rb", C_EXTENSION}, + {"MODULE.EXE", "rb", C_EXTENSION}, + #else ++#ifdef Py_DEBUG ++ {"_d.so", "rb", C_EXTENSION}, ++ {"module_d.so", "rb", C_EXTENSION}, ++#endif + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, + #endif +Index: b/Python/sysmodule.c +=================================================================== +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1524,6 +1524,12 @@ _PySys_Init(void) + PyString_FromString("legacy")); + #endif + ++#ifdef Py_DEBUG ++ PyDict_SetItemString(sysdict, "pydebug", Py_True); ++#else ++ PyDict_SetItemString(sysdict, "pydebug", Py_False); ++#endif ++ + #undef SET_SYS_FROM_STRING + if (PyErr_Occurred()) + return NULL; +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -777,7 +777,7 @@ AC_SUBST(LIBRARY) + AC_MSG_CHECKING(LIBRARY) + if test -z "$LIBRARY" + then +- LIBRARY='libpython$(VERSION).a' ++ LIBRARY='libpython$(VERSION)$(DEBUG_EXT).a' + fi + AC_MSG_RESULT($LIBRARY) + +@@ -923,8 +923,8 @@ if test $enable_shared = "yes"; then + INSTSONAME="$LDLIBRARY".$SOVERSION + ;; + Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*|OpenBSD*) +- LDLIBRARY='libpython$(VERSION).so' +- BLDLIBRARY='-L. -lpython$(VERSION)' ++ LDLIBRARY='libpython$(VERSION)$(DEBUG_EXT).so' ++ BLDLIBRARY='-L. -lpython$(VERSION)$(DEBUG_EXT)' + RUNSHARED=LD_LIBRARY_PATH=`pwd`${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}} + case $ac_sys_system in + FreeBSD*) +@@ -1050,6 +1050,12 @@ else AC_MSG_RESULT(no); Py_DEBUG='false' + fi], + [AC_MSG_RESULT(no)]) + ++if test "$Py_DEBUG" = 'true' ++then ++ DEBUG_EXT=_d ++fi ++AC_SUBST(DEBUG_EXT) ++ + # XXX Shouldn't the code above that fiddles with BASECFLAGS and OPT be + # merged with this chunk of code? + +@@ -2129,7 +2135,7 @@ then + esac + ;; + CYGWIN*) SO=.dll;; +- *) SO=.so;; ++ *) SO=$DEBUG_EXT.so;; + esac + else + # this might also be a termcap variable, see #610332 +Index: b/Lib/distutils/tests/test_build_ext.py +=================================================================== +--- a/Lib/distutils/tests/test_build_ext.py ++++ b/Lib/distutils/tests/test_build_ext.py +@@ -295,8 +295,8 @@ class BuildExtTestCase(support.TempdirMa + finally: + os.chdir(old_wd) + self.assertTrue(os.path.exists(so_file)) +- self.assertEqual(os.path.splitext(so_file)[-1], +- sysconfig.get_config_var('SO')) ++ so_ext = sysconfig.get_config_var('SO') ++ self.assertEqual(so_file[len(so_file)-len(so_ext):], so_ext) + so_dir = os.path.dirname(so_file) + self.assertEqual(so_dir, other_tmp_dir) + cmd.compiler = None +@@ -304,8 +304,7 @@ class BuildExtTestCase(support.TempdirMa + cmd.run() + so_file = cmd.get_outputs()[0] + self.assertTrue(os.path.exists(so_file)) +- self.assertEqual(os.path.splitext(so_file)[-1], +- sysconfig.get_config_var('SO')) ++ self.assertEqual(so_file[len(so_file)-len(so_ext):], so_ext) + so_dir = os.path.dirname(so_file) + self.assertEqual(so_dir, cmd.build_lib) + +Index: b/Lib/distutils/tests/test_build.py +=================================================================== +--- a/Lib/distutils/tests/test_build.py ++++ b/Lib/distutils/tests/test_build.py +@@ -20,10 +20,6 @@ class BuildTestCase(support.TempdirManag + # if not specified, plat_name gets the current platform + self.assertEqual(cmd.plat_name, get_platform()) + +- # build_purelib is build + lib +- wanted = os.path.join(cmd.build_base, 'lib') +- self.assertEqual(cmd.build_purelib, wanted) +- + # build_platlib is 'build/lib.platform-x.x[-pydebug]' + # examples: + # build/lib.macosx-10.3-i386-2.7 +@@ -34,6 +30,10 @@ class BuildTestCase(support.TempdirManag + wanted = os.path.join(cmd.build_base, 'lib' + plat_spec) + self.assertEqual(cmd.build_platlib, wanted) + ++ # build_purelib is build + lib ++ wanted = os.path.join(cmd.build_base, 'lib' + plat_spec) ++ self.assertEqual(cmd.build_purelib, wanted) ++ + # by default, build_lib = build_purelib + self.assertEqual(cmd.build_lib, cmd.build_purelib) + --- python2.7-2.7.15.orig/debian/patches/disable-sem-check.diff +++ python2.7-2.7.15/debian/patches/disable-sem-check.diff @@ -0,0 +1,30 @@ +# DP: Assume working semaphores on Linux, don't rely on running kernel for the check. + +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -4058,6 +4058,11 @@ int main(void) { + [ac_cv_posix_semaphores_enabled=no], + [ac_cv_posix_semaphores_enabled=yes]) + ) ++case $ac_sys_system in ++ Linux*) ++ # assume enabled, see https://launchpad.net/bugs/630511 ++ ac_cv_posix_semaphores_enabled=yes ++esac + AC_MSG_RESULT($ac_cv_posix_semaphores_enabled) + if test $ac_cv_posix_semaphores_enabled = no + then +@@ -4094,6 +4099,11 @@ int main(void){ + [ac_cv_broken_sem_getvalue=yes], + [ac_cv_broken_sem_getvalue=yes]) + ) ++case $ac_sys_system in ++ Linux*) ++ # assume enabled, see https://launchpad.net/bugs/630511 ++ ac_cv_broken_sem_getvalue=no ++esac + AC_MSG_RESULT($ac_cv_broken_sem_getvalue) + if test $ac_cv_broken_sem_getvalue = yes + then --- python2.7-2.7.15.orig/debian/patches/disable-utimes.diff +++ python2.7-2.7.15/debian/patches/disable-utimes.diff @@ -0,0 +1,13 @@ +# DP: disable check for utimes function, which is broken in glibc-2.3.2 + +--- a/configure.ac ++++ b/configure.ac +@@ -2698,7 +2698,7 @@ + setsid setpgid setpgrp setuid setvbuf snprintf \ + sigaction siginterrupt sigrelse strftime \ + sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ +- truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty) ++ truncate uname unsetenv waitpid wait3 wait4 wcscoll _getpty) + + # For some functions, having a definition is not sufficient, since + # we want to take their address. --- python2.7-2.7.15.orig/debian/patches/distutils-install-layout.diff +++ python2.7-2.7.15/debian/patches/distutils-install-layout.diff @@ -0,0 +1,406 @@ +# DP: distutils: Add an option --install-layout=deb, which +# DP: - installs into $prefix/dist-packages instead of $prefix/site-packages. +# DP: - doesn't encode the python version into the egg name. + +Index: b/Doc/install/index.rst +=================================================================== +--- a/Doc/install/index.rst ++++ b/Doc/install/index.rst +@@ -255,6 +255,8 @@ is pure Python or contains extensions (" + +-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Platform | Standard installation location | Default value | Notes | + +=================+=====================================================+==================================================+=======+ ++| Debian/Ubuntu | :file:`{prefix}/lib/python{X.Y}/dist-packages` | :file:`/usr/local/lib/python{X.Y}/dist-packages` | \(0) | +++-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Unix (pure) | :file:`{prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1) | + +-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Unix (non-pure) | :file:`{exec-prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1) | +@@ -264,6 +266,14 @@ is pure Python or contains extensions (" + + Notes: + ++(0) ++ Starting with Python-2.6 Debian/Ubuntu uses for the Python which comes within ++ the Linux distribution a non-default name for the installation directory. This ++ is to avoid overwriting of the python modules which come with the distribution, ++ which unfortunately is the upstream behaviour of the installation tools. The ++ non-default name in :file:`/usr/local` is used not to overwrite a local python ++ installation (defaulting to :file:`/usr/local`). ++ + (1) + Most Linux distributions include Python as a standard part of the system, so + :file:`{prefix}` and :file:`{exec-prefix}` are usually both :file:`/usr` on +@@ -448,6 +458,15 @@ them to go in :file:`/usr/local/lib/pyth + + /usr/bin/python setup.py install --prefix=/usr/local + ++Starting with Python-2.6 Debian/Ubuntu does use ++:file:`/usr/lib/python{X.Y}/dist-packages` and ++:file:`/usr/local/lib/python{X.Y}/dist-packages` for the installation ++of python modules included in the Linux distribution. To overwrite ++the name of the site directory, explicitely use the :option:`--prefix` ++option, however make sure that the installation path is included in ++``sys.path``. For packaging of python modules for Debian/Ubuntu, use ++the new ``setup.py install`` option :option:`--install-layout=deb`. ++ + Another possibility is a network filesystem where the name used to write to a + remote directory is different from the name used to read it: for example, the + Python interpreter accessed as :file:`/usr/local/bin/python` might search for +@@ -699,6 +718,17 @@ Add-on Python modules might then belong + import them, this directory must be added to ``sys.path``. There are several + different ways to add the directory. + ++On Debian/Ubuntu, starting with Python-2.6 the convention for system ++installed packages is to put then in the ++:file:`/usr/lib/python{X.Y}/dist-packages/` directory, and for locally ++installed packages is to put them in the ++:file:`/usr/lib/python{X.Y}/dist-packages/` directory. To share the ++locally installed packages for the system provided Python with the ++locally installed packages of a local python installation, make ++:file:`/usr/lib/python{X.Y}/dist-packages/` a symbolic link to the ++:file:`{...}/site-packages/` directory of your local python ++installation. ++ + The most convenient way is to add a path configuration file to a directory + that's already on Python's path, usually to the :file:`.../site-packages/` + directory. Path configuration files have an extension of :file:`.pth`, and each +Index: b/Lib/distutils/command/install.py +=================================================================== +--- a/Lib/distutils/command/install.py ++++ b/Lib/distutils/command/install.py +@@ -47,6 +47,20 @@ INSTALL_SCHEMES = { + 'scripts': '$base/bin', + 'data' : '$base', + }, ++ 'unix_local': { ++ 'purelib': '$base/local/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/local/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/local/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/local/bin', ++ 'data' : '$base/local', ++ }, ++ 'deb_system': { ++ 'purelib': '$base/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/bin', ++ 'data' : '$base', ++ }, + 'unix_home': { + 'purelib': '$base/lib/python', + 'platlib': '$base/lib/python', +@@ -154,6 +168,9 @@ class install (Command): + + ('record=', None, + "filename in which to record list of installed files"), ++ ++ ('install-layout=', None, ++ "installation layout to choose (known values: deb, unix)"), + ] + + boolean_options = ['compile', 'force', 'skip-build', 'user'] +@@ -168,6 +185,7 @@ class install (Command): + self.exec_prefix = None + self.home = None + self.user = 0 ++ self.prefix_option = None + + # These select only the installation base; it's up to the user to + # specify the installation scheme (currently, that means supplying +@@ -189,6 +207,9 @@ class install (Command): + self.install_userbase = USER_BASE + self.install_usersite = USER_SITE + ++ # enable custom installation, known values: deb ++ self.install_layout = None ++ + self.compile = None + self.optimize = None + +@@ -421,6 +442,7 @@ class install (Command): + self.install_base = self.install_platbase = self.home + self.select_scheme("unix_home") + else: ++ self.prefix_option = self.prefix + if self.prefix is None: + if self.exec_prefix is not None: + raise DistutilsOptionError, \ +@@ -435,7 +457,23 @@ class install (Command): + + self.install_base = self.prefix + self.install_platbase = self.exec_prefix +- self.select_scheme("unix_prefix") ++ if self.install_layout: ++ if self.install_layout.lower() in ['deb']: ++ self.select_scheme("deb_system") ++ elif self.install_layout.lower() in ['posix', 'unix']: ++ self.select_scheme("unix_prefix") ++ else: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") ++ elif (self.prefix_option and os.path.normpath(self.prefix) != '/usr/local') \ ++ or 'PYTHONUSERBASE' in os.environ \ ++ or 'real_prefix' in sys.__dict__: ++ self.select_scheme("unix_prefix") ++ else: ++ if os.path.normpath(self.prefix) == '/usr/local': ++ self.select_scheme("deb_system") ++ else: ++ self.select_scheme("unix_local") + + # finalize_unix () + +Index: b/Lib/distutils/command/install_egg_info.py +=================================================================== +--- a/Lib/distutils/command/install_egg_info.py ++++ b/Lib/distutils/command/install_egg_info.py +@@ -14,18 +14,37 @@ class install_egg_info(Command): + description = "Install package's PKG-INFO metadata as an .egg-info file" + user_options = [ + ('install-dir=', 'd', "directory to install to"), ++ ('install-layout', None, "custom installation layout"), + ] + + def initialize_options(self): + self.install_dir = None ++ self.install_layout = None ++ self.prefix_option = None + + def finalize_options(self): + self.set_undefined_options('install_lib',('install_dir','install_dir')) +- basename = "%s-%s-py%s.egg-info" % ( +- to_filename(safe_name(self.distribution.get_name())), +- to_filename(safe_version(self.distribution.get_version())), +- sys.version[:3] +- ) ++ self.set_undefined_options('install',('install_layout','install_layout')) ++ self.set_undefined_options('install',('prefix_option','prefix_option')) ++ if self.install_layout: ++ basename = "%s-%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())) ++ ) ++ if not self.install_layout.lower() in ['deb']: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") ++ elif self.prefix_option or 'real_prefix' in sys.__dict__: ++ basename = "%s-%s-py%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())), ++ sys.version[:3] ++ ) ++ else: ++ basename = "%s-%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())) ++ ) + self.target = os.path.join(self.install_dir, basename) + self.outputs = [self.target] + +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -115,6 +115,7 @@ def get_python_lib(plat_specific=0, stan + If 'prefix' is supplied, use it instead of sys.prefix or + sys.exec_prefix -- i.e., ignore 'plat_specific'. + """ ++ is_default_prefix = not prefix or os.path.normpath(prefix) in ('/usr', '/usr/local') + if prefix is None: + prefix = plat_specific and EXEC_PREFIX or PREFIX + +@@ -123,6 +124,8 @@ def get_python_lib(plat_specific=0, stan + "lib", "python" + get_python_version()) + if standard_lib: + return libpython ++ elif is_default_prefix and 'PYTHONUSERBASE' not in os.environ and 'real_prefix' not in sys.__dict__: ++ return os.path.join(libpython, "dist-packages") + else: + return os.path.join(libpython, "site-packages") + +Index: b/Lib/site.py +=================================================================== +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -273,6 +273,13 @@ def addusersitepackages(known_paths): + + if ENABLE_USER_SITE and os.path.isdir(user_site): + addsitedir(user_site, known_paths) ++ if ENABLE_USER_SITE: ++ for dist_libdir in ("local/lib", "lib"): ++ user_site = os.path.join(USER_BASE, dist_libdir, ++ "python" + sys.version[:3], ++ "dist-packages") ++ if os.path.isdir(user_site): ++ addsitedir(user_site, known_paths) + return known_paths + + def getsitepackages(): +Index: b/Lib/sysconfig.py +=================================================================== +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -16,6 +16,26 @@ _INSTALL_SCHEMES = { + 'scripts': '{base}/bin', + 'data': '{base}', + }, ++ 'posix_local': { ++ 'stdlib': '{base}/lib/python{py_version_short}', ++ 'platstdlib': '{platbase}/lib/python{py_version_short}', ++ 'purelib': '{base}/local/lib/python{py_version_short}/dist-packages', ++ 'platlib': '{platbase}/local/lib/python{py_version_short}/dist-packages', ++ 'include': '{base}/local/include/python{py_version_short}', ++ 'platinclude': '{platbase}/local/include/python{py_version_short}', ++ 'scripts': '{base}/local/bin', ++ 'data': '{base}/local', ++ }, ++ 'deb_system': { ++ 'stdlib': '{base}/lib/python{py_version_short}', ++ 'platstdlib': '{platbase}/lib/python{py_version_short}', ++ 'purelib': '{base}/lib/python{py_version_short}/dist-packages', ++ 'platlib': '{platbase}/lib/python{py_version_short}/dist-packages', ++ 'include': '{base}/include/python{py_version_short}', ++ 'platinclude': '{platbase}/include/python{py_version_short}', ++ 'scripts': '{base}/bin', ++ 'data': '{base}', ++ }, + 'posix_home': { + 'stdlib': '{base}/lib/python', + 'platstdlib': '{base}/lib/python', +@@ -134,7 +154,7 @@ def is_python_build(): + _PYTHON_BUILD = is_python_build() + + if _PYTHON_BUILD: +- for scheme in ('posix_prefix', 'posix_home'): ++ for scheme in ('posix_prefix', 'posix_local', 'deb_system', 'posix_home'): + _INSTALL_SCHEMES[scheme]['include'] = '{projectbase}/Include' + _INSTALL_SCHEMES[scheme]['platinclude'] = '{srcdir}' + +@@ -168,8 +188,11 @@ def _expand_vars(scheme, vars): + + def _get_default_scheme(): + if os.name == 'posix': +- # the default scheme for posix is posix_prefix +- return 'posix_prefix' ++ # the default scheme for posix on Debian/Ubuntu is posix_local ++ # FIXME: return dist-packages/posix_prefix only for ++ # is_default_prefix and 'PYTHONUSERBASE' not in os.environ and 'real_prefix' not in sys.__dict__ ++ # is_default_prefix = not prefix or os.path.normpath(prefix) in ('/usr', '/usr/local') ++ return 'posix_local' + return os.name + + def _getuserbase(): +@@ -315,7 +338,7 @@ def get_makefile_filename(): + """Return the path of the Makefile.""" + if _PYTHON_BUILD: + return os.path.join(_PROJECT_BASE, "Makefile") +- return os.path.join(get_path('platstdlib'), "config", "Makefile") ++ return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config", "Makefile") + + # Issue #22199: retain undocumented private name for compatibility + _get_makefile_filename = get_makefile_filename +@@ -447,7 +470,7 @@ def get_config_h_filename(): + else: + inc_dir = _PROJECT_BASE + else: +- inc_dir = get_path('platinclude') ++ inc_dir = get_path('platinclude').replace("/usr/local","/usr",1) + return os.path.join(inc_dir, 'pyconfig.h') + + def get_scheme_names(): +Index: b/Lib/test/test_import.py +=================================================================== +--- a/Lib/test/test_import.py ++++ b/Lib/test/test_import.py +@@ -301,7 +301,7 @@ class ImportTests(unittest.TestCase): + with check_warnings(('', ImportWarning)): + # Just a random non-package directory we always expect to be + # somewhere in sys.path... +- self.assertRaises(ImportError, __import__, "site-packages") ++ self.assertRaises(ImportError, __import__, "dist-packages") + + def test_import_by_filename(self): + path = os.path.abspath(TESTFN) +Index: b/Lib/test/test_site.py +=================================================================== +--- a/Lib/test/test_site.py ++++ b/Lib/test/test_site.py +@@ -253,10 +253,13 @@ class HelperFunctionsTests(unittest.Test + elif os.sep == '/': + # OS X, Linux, FreeBSD, etc + self.assertEqual(len(dirs), 2) +- wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3], +- 'site-packages') ++ wanted = os.path.join('xoxo', 'local', 'lib', ++ 'python' + sys.version[:3], ++ 'dist-packages') + self.assertEqual(dirs[0], wanted) +- wanted = os.path.join('xoxo', 'lib', 'site-python') ++ wanted = os.path.join('xoxo', 'lib', ++ 'python' + sys.version[:3], ++ 'dist-packages') + self.assertEqual(dirs[1], wanted) + else: + # other platforms +Index: b/Lib/test/test_sysconfig.py +=================================================================== +--- a/Lib/test/test_sysconfig.py ++++ b/Lib/test/test_sysconfig.py +@@ -239,8 +239,8 @@ class TestSysConfig(unittest.TestCase): + self.assertTrue(os.path.isfile(config_h), config_h) + + def test_get_scheme_names(self): +- wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user', +- 'posix_home', 'posix_prefix', 'posix_user') ++ wanted = ('deb_system', 'nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user', ++ 'posix_home', 'posix_local', 'posix_prefix', 'posix_user') + self.assertEqual(get_scheme_names(), wanted) + + @unittest.skipIf(sys.platform.startswith('win'), +Index: b/Lib/distutils/tests/test_install.py +=================================================================== +--- a/Lib/distutils/tests/test_install.py ++++ b/Lib/distutils/tests/test_install.py +@@ -194,7 +194,7 @@ class InstallTestCase(support.TempdirMan + + found = [os.path.basename(line) for line in content.splitlines()] + expected = ['hello.py', 'hello.pyc', 'sayhi', +- 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] ++ 'UNKNOWN-0.0.0.egg-info'] + self.assertEqual(found, expected) + + def test_record_extensions(self): +@@ -224,7 +224,7 @@ class InstallTestCase(support.TempdirMan + + found = [os.path.basename(line) for line in content.splitlines()] + expected = [_make_ext_name('xx'), +- 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] ++ 'UNKNOWN-0.0.0.egg-info'] + self.assertEqual(found, expected) + + def test_debug_mode(self): +Index: b/Lib/distutils/tests/test_bdist_dumb.py +=================================================================== +--- a/Lib/distutils/tests/test_bdist_dumb.py ++++ b/Lib/distutils/tests/test_bdist_dumb.py +@@ -87,7 +87,7 @@ class BuildDumbTestCase(support.TempdirM + fp.close() + + contents = sorted(os.path.basename(fn) for fn in contents) +- wanted = ['foo-0.1-py%s.%s.egg-info' % sys.version_info[:2], 'foo.py'] ++ wanted = ['foo-0.1.egg-info', 'foo.py'] + if not sys.dont_write_bytecode: + wanted.append('foo.pyc') + self.assertEqual(contents, sorted(wanted)) +Index: b/Lib/pydoc.py +=================================================================== +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -392,6 +392,7 @@ class Doc: + 'marshal', 'posix', 'signal', 'sys', + 'thread', 'zipimport') or + (file.startswith(basedir) and ++ not file.startswith(os.path.join(basedir, 'dist-packages')) and + not file.startswith(os.path.join(basedir, 'site-packages')))) and + object.__name__ not in ('xml.etree', 'test.pydoc_mod')): + if docloc.startswith(("http://", "https://")): --- python2.7-2.7.15.orig/debian/patches/distutils-link.diff +++ python2.7-2.7.15/debian/patches/distutils-link.diff @@ -0,0 +1,20 @@ +# DP: Don't add standard library dirs to library_dirs and runtime_library_dirs. + +Index: b/Lib/distutils/unixccompiler.py +=================================================================== +--- a/Lib/distutils/unixccompiler.py ++++ b/Lib/distutils/unixccompiler.py +@@ -157,7 +157,12 @@ class UnixCCompiler(CCompiler): + objects, output_dir = self._fix_object_args(objects, output_dir) + libraries, library_dirs, runtime_library_dirs = \ + self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) +- ++ # filter out standard library paths, which are not explicitely needed ++ # for linking ++ library_dirs = [dir for dir in library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] ++ runtime_library_dirs = [dir for dir in runtime_library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, + libraries) + if type(output_dir) not in (StringType, NoneType): --- python2.7-2.7.15.orig/debian/patches/distutils-sysconfig.diff +++ python2.7-2.7.15/debian/patches/distutils-sysconfig.diff @@ -0,0 +1,53 @@ +# DP: Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, +# DP: CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -174,10 +174,12 @@ def customize_compiler(compiler): + _osx_support.customize_compiler(_config_vars) + _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True' + +- (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ +- get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', +- 'CCSHARED', 'LDSHARED', 'SO', 'AR', +- 'ARFLAGS') ++ (cc, cxx, opt, cflags, extra_cflags, basecflags, ++ ccshared, ldshared, so_ext, ar, ar_flags, ++ configure_cppflags, configure_cflags, configure_ldflags) = \ ++ get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', 'EXTRA_CFLAGS', 'BASECFLAGS', ++ 'CCSHARED', 'LDSHARED', 'SO', 'AR', 'ARFLAGS', ++ 'CONFIGURE_CPPFLAGS', 'CONFIGURE_CFLAGS', 'CONFIGURE_LDFLAGS') + + if 'CC' in os.environ: + newcc = os.environ['CC'] +@@ -198,13 +200,27 @@ def customize_compiler(compiler): + cpp = cc + " -E" # not always + if 'LDFLAGS' in os.environ: + ldshared = ldshared + ' ' + os.environ['LDFLAGS'] ++ elif configure_ldflags: ++ ldshared = ldshared + ' ' + configure_ldflags ++ if 'BASECFLAGS' in os.environ: ++ basecflags = os.environ['BASECFLAGS'] ++ if 'OPT' in os.environ: ++ opt = os.environ['OPT'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, extra_cflags) if x) + if 'CFLAGS' in os.environ: +- cflags = opt + ' ' + os.environ['CFLAGS'] ++ cflags = ' '.join(str(x) for x in (opt, basecflags, os.environ['CFLAGS'], extra_cflags) if x) + ldshared = ldshared + ' ' + os.environ['CFLAGS'] ++ elif configure_cflags: ++ cflags = ' '.join(str(x) for x in (opt, basecflags, configure_cflags, extra_cflags) if x) ++ ldshared = ldshared + ' ' + configure_cflags + if 'CPPFLAGS' in os.environ: + cpp = cpp + ' ' + os.environ['CPPFLAGS'] + cflags = cflags + ' ' + os.environ['CPPFLAGS'] + ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] ++ elif configure_cppflags: ++ cpp = cpp + ' ' + configure_cppflags ++ cflags = cflags + ' ' + configure_cppflags ++ ldshared = ldshared + ' ' + configure_cppflags + if 'AR' in os.environ: + ar = os.environ['AR'] + if 'ARFLAGS' in os.environ: --- python2.7-2.7.15.orig/debian/patches/doc-nodownload.diff +++ python2.7-2.7.15/debian/patches/doc-nodownload.diff @@ -0,0 +1,13 @@ +# DP: Don't try to download documentation tools + +--- a/Doc/Makefile ++++ b/Doc/Makefile +@@ -57,7 +57,7 @@ + + update: clean checkout + +-build: checkout ++build: + mkdir -p build/$(BUILDER) build/doctrees + $(PYTHON) tools/sphinx-build.py $(ALLSPHINXOPTS) + @echo --- python2.7-2.7.15.orig/debian/patches/enable-fpectl.diff +++ python2.7-2.7.15/debian/patches/enable-fpectl.diff @@ -0,0 +1,16 @@ +# DP: Enable the build of the fpectl module. + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -1399,6 +1399,9 @@ class PyBuildExt(build_ext): + else: + missing.append('_curses_panel') + ++ #fpectl fpectlmodule.c ... ++ exts.append( Extension('fpectl', ['fpectlmodule.c']) ) ++ + # Andrew Kuchling's zlib module. Note that some versions of zlib + # 1.1.3 have security problems. See CERT Advisory CA-2002-07: + # http://www.cert.org/advisories/CA-2002-07.html --- python2.7-2.7.15.orig/debian/patches/enable-sqlite-loadext.diff +++ python2.7-2.7.15/debian/patches/enable-sqlite-loadext.diff @@ -0,0 +1,15 @@ +# DP: Allow loading of extensions in the sqlite module + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -1200,7 +1200,7 @@ class PyBuildExt(build_ext): + sqlite_defines.append(('MODULE_NAME', '\\"sqlite3\\"')) + + # Comment this out if you want the sqlite3 module to be able to load extensions. +- sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1")) ++ # sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1")) + + if host_platform == 'darwin': + # In every directory on the search path search for a dynamic --- python2.7-2.7.15.orig/debian/patches/ensurepip-disabled.diff +++ python2.7-2.7.15/debian/patches/ensurepip-disabled.diff @@ -0,0 +1,44 @@ +# DP: Disable ensurepip in Debian for now. + +Index: b/Lib/ensurepip/__init__.py +=================================================================== +--- a/Lib/ensurepip/__init__.py ++++ b/Lib/ensurepip/__init__.py +@@ -12,6 +12,21 @@ import tempfile + + __all__ = ["version", "bootstrap"] + ++def _ensurepip_is_disabled_in_debian(): ++ if True: ++ print ('''\ ++ensurepip is disabled in Debian/Ubuntu for the system python. ++ ++Python modules For the system python are usually handled by dpkg and apt-get. ++ ++ apt-get install python- ++ ++Install the python-pip package to use pip itself. Using pip together ++with the system python might have unexpected results for any system installed ++module, so use it on your own risk, or make sure to only use it in virtual ++environments. ++''') ++ sys.exit(1) + + _PROJECTS = [ + ("setuptools"), +@@ -33,6 +48,7 @@ def version(): + """ + Returns a string specifying the bundled version of pip. + """ ++ _ensurepip_is_disabled_in_debian() + whl_name = 'pip' + wheel_names = glob.glob('/usr/share/python-wheels/%s-*.whl' % whl_name) + if len(wheel_names) == 1: +@@ -76,6 +92,7 @@ def _bootstrap(root=None, upgrade=False, + + Note that calling this function will alter both sys.path and os.environ. + """ ++ _ensurepip_is_disabled_in_debian() + if altinstall and default_pip: + raise ValueError("Cannot use altinstall and default_pip together") + --- python2.7-2.7.15.orig/debian/patches/ensurepip-wheels.diff +++ python2.7-2.7.15/debian/patches/ensurepip-wheels.diff @@ -0,0 +1,135 @@ +# DP: Let ensurepip use the system wheels, not the ones from the python source. + +Index: b/Lib/ensurepip/__init__.py +=================================================================== +--- a/Lib/ensurepip/__init__.py ++++ b/Lib/ensurepip/__init__.py +@@ -1,6 +1,7 @@ + #!/usr/bin/env python2 + from __future__ import print_function + ++import glob + import os + import os.path + import pkgutil +@@ -12,13 +13,9 @@ import tempfile + __all__ = ["version", "bootstrap"] + + +-_SETUPTOOLS_VERSION = "39.0.1" +- +-_PIP_VERSION = "10.0.1" +- + _PROJECTS = [ +- ("setuptools", _SETUPTOOLS_VERSION), +- ("pip", _PIP_VERSION), ++ ("setuptools"), ++ ("pip"), + ] + + +@@ -36,7 +33,11 @@ def version(): + """ + Returns a string specifying the bundled version of pip. + """ +- return _PIP_VERSION ++ whl_name = 'pip' ++ wheel_names = glob.glob('/usr/share/python-wheels/%s-*.whl' % whl_name) ++ if len(wheel_names) == 1: ++ return os.path.basename(wheel_names[0]).split('-')[1] ++ raise RuntimeError('missing dependency wheel %s. Installation of the python-%s-whl package is needed to use ensurepip.' % (whl_name, whl_name)) + + + def _disable_pip_configuration_settings(): +@@ -93,21 +94,53 @@ def _bootstrap(root=None, upgrade=False, + # omit pip and easy_install + os.environ["ENSUREPIP_OPTIONS"] = "install" + ++ # Debian: The bundled wheels are useless to us because we must use ones ++ # crafted from source code in the archive. As we build the virtual ++ # environment, copy the wheels from the system location into the virtual ++ # environment, and place those wheels on sys.path. ++ def copy_wheels(wheels, destdir, paths): ++ for project in wheels: ++ wheel_names = glob.glob( ++ '/usr/share/python-wheels/{}-*.whl'.format(project)) ++ if len(wheel_names) == 0: ++ raise RuntimeError('missing dependency wheel %s. Installation of the python-%s-whl package is needed to use ensurepip.' % (project, project)) ++ assert len(wheel_names) == 1, wheel_names ++ wheel_name = os.path.basename(wheel_names[0]) ++ path = os.path.join('/usr/share/python-wheels', wheel_name) ++ with open(path, 'rb') as fp: ++ whl = fp.read() ++ dest = os.path.join(destdir, wheel_name) ++ with open(dest, 'wb') as fp: ++ fp.write(whl) ++ paths.append(dest) ++ ++ # check that the python-{pip,setuptools}-whl packages are installed ++ missing = [] ++ for project in reversed(_PROJECTS): ++ wheel_names = glob.glob('/usr/share/python-wheels/%s-*.whl' % project) ++ if len(wheel_names) != 1: ++ missing.append(project) ++ if missing: ++ raise RuntimeError('missing wheel(s) %s. Installation of the %s package(s) is needed to use ensurepip.' \ ++ % (', '.join([missing]), ++ ', '.join(['python-%s-whl' % m for m in missing])) \ ++ ) ++ + tmpdir = tempfile.mkdtemp() ++ ++ for project in _PROJECTS: ++ try: ++ with open('/usr/share/python-wheels/%s.dependencies' % project) as fp: ++ dependencies = [line[:-1].split()[0] for line in fp.readlines()] ++ except IOError: ++ dependencies = [] ++ copy_wheels(dependencies, tmpdir, sys.path) ++ + try: + # Put our bundled wheels into a temporary directory and construct the + # additional paths that need added to sys.path + additional_paths = [] +- for project, version in _PROJECTS: +- wheel_name = "{}-{}-py2.py3-none-any.whl".format(project, version) +- whl = pkgutil.get_data( +- "ensurepip", +- "_bundled/{}".format(wheel_name), +- ) +- with open(os.path.join(tmpdir, wheel_name), "wb") as fp: +- fp.write(whl) +- +- additional_paths.append(os.path.join(tmpdir, wheel_name)) ++ copy_wheels(_PROJECTS, tmpdir, additional_paths) + + # Construct the arguments to be passed to the pip command + args = ["install", "--no-index", "--find-links", tmpdir] +@@ -120,7 +153,7 @@ def _bootstrap(root=None, upgrade=False, + if verbosity: + args += ["-" + "v" * verbosity] + +- return _run_pip(args + [p[0] for p in _PROJECTS], additional_paths) ++ return _run_pip(args + _PROJECTS, additional_paths) + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + +@@ -136,7 +169,8 @@ def _uninstall_helper(verbosity=0): + return + + # If the pip version doesn't match the bundled one, leave it alone +- if pip.__version__ != _PIP_VERSION: ++ # Disabled for Debian, always using the version from the python3-pip package. ++ if False and pip.__version__ != _PIP_VERSION: + msg = ("ensurepip will only uninstall a matching version " + "({!r} installed, {!r} bundled)") + print(msg.format(pip.__version__, _PIP_VERSION), file=sys.stderr) +@@ -149,7 +183,7 @@ def _uninstall_helper(verbosity=0): + if verbosity: + args += ["-" + "v" * verbosity] + +- return _run_pip(args + [p[0] for p in reversed(_PROJECTS)]) ++ return _run_pip(args + reversed(_PROJECTS)) + + + def _main(argv=None): --- python2.7-2.7.15.orig/debian/patches/ext-no-libpython-link.diff +++ python2.7-2.7.15/debian/patches/ext-no-libpython-link.diff @@ -0,0 +1,24 @@ +# DP: Don't link extensions with the shared libpython library. + +Index: b/Lib/distutils/command/build_ext.py +=================================================================== +--- a/Lib/distutils/command/build_ext.py ++++ b/Lib/distutils/command/build_ext.py +@@ -237,7 +237,7 @@ class build_ext (Command): + # For building extensions with a shared Python library, + # Python's library directory must be appended to library_dirs + # See Issues: #1600860, #4366 +- if (sysconfig.get_config_var('Py_ENABLE_SHARED')): ++ if False and (sysconfig.get_config_var('Py_ENABLE_SHARED')): + if not sysconfig.python_build: + # building third party extensions + self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) +@@ -758,7 +758,7 @@ class build_ext (Command): + return ext.libraries + else: + from distutils import sysconfig +- if sysconfig.get_config_var('Py_ENABLE_SHARED'): ++ if False and sysconfig.get_config_var('Py_ENABLE_SHARED'): + template = "python%d.%d" + pythonlib = (template % + (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff)) --- python2.7-2.7.15.orig/debian/patches/fix-sslv3-test.diff +++ python2.7-2.7.15/debian/patches/fix-sslv3-test.diff @@ -0,0 +1,18 @@ +Description: properly handle Ubuntu's openssl having OP_NO_SSLv3 forced on by default +Author: Marc Deslauriers +Forwarded: yes, http://bugs.python.org/issue25724 + +Index: b/Lib/test/test_ssl.py +=================================================================== +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -777,7 +777,8 @@ class ContextTests(unittest.TestCase): + ctx.options = (ctx.options & ~ssl.OP_NO_TLSv1) + self.assertEqual(default, ctx.options) + ctx.options = 0 +- self.assertEqual(0, ctx.options) ++ # Ubuntu has OP_NO_SSLv3 forced on by default ++ self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3) + else: + with self.assertRaises(ValueError): + ctx.options = 0 --- python2.7-2.7.15.orig/debian/patches/git-updates.diff +++ python2.7-2.7.15/debian/patches/git-updates.diff @@ -0,0 +1,26028 @@ +# DP: hg updates of the 2.7 release branch (until 2018-09-26). + +# git diff ca079a3ea30098aff3197c559a0e32d42dda6d84 65fa1264a308a94e24afa76f41a68708a346738f | filterdiff -x ?/.hgignore -x ?/.hgeol -x ?/.hgtags -x ?/.hgtouch -x ?/.gitignore -x ?/.gitattributes -x '?/.github/*' -x '?/.git*' -x ?/.codecov.yml -x ?/.travis.yml -x ?/configure --remove-timestamps + +diff --git a/Doc/README.txt b/Doc/README.txt +index 4f8e9f8f14..a362ecca94 100644 +--- a/Doc/README.txt ++++ b/Doc/README.txt +@@ -15,7 +15,7 @@ Building the docs + + You need to have Sphinx installed; it is the toolset + used to build the docs. It is not included in this tree, but maintained +-separately and available from PyPI . ++separately and available from PyPI . + + + Using make +diff --git a/Doc/c-api/capsule.rst b/Doc/c-api/capsule.rst +index b8642d0aba..fd4279cd96 100644 +--- a/Doc/c-api/capsule.rst ++++ b/Doc/c-api/capsule.rst +@@ -9,6 +9,8 @@ Capsules + + Refer to :ref:`using-capsules` for more information on using these objects. + ++.. versionadded:: 2.7 ++ + + .. c:type:: PyCapsule + +@@ -19,6 +21,7 @@ Refer to :ref:`using-capsules` for more information on using these objects. + regular import mechanism can be used to access C APIs defined in dynamically + loaded modules. + ++ + .. c:type:: PyCapsule_Destructor + + The type of a destructor callback for a capsule. Defined as:: +@@ -104,8 +107,8 @@ Refer to :ref:`using-capsules` for more information on using these objects. + import the module conventionally (using :c:func:`PyImport_ImportModule`). + + Return the capsule's internal *pointer* on success. On failure, set an +- exception and return *NULL*. However, if :c:func:`PyCapsule_Import` failed to +- import the module, and *no_block* was true, no exception is set. ++ exception and return *NULL*. ++ + + .. c:function:: int PyCapsule_IsValid(PyObject *capsule, const char *name) + +@@ -122,18 +125,21 @@ Refer to :ref:`using-capsules` for more information on using these objects. + Return a nonzero value if the object is valid and matches the name passed in. + Return ``0`` otherwise. This function will not fail. + ++ + .. c:function:: int PyCapsule_SetContext(PyObject *capsule, void *context) + + Set the context pointer inside *capsule* to *context*. + + Return ``0`` on success. Return nonzero and set an exception on failure. + ++ + .. c:function:: int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor) + + Set the destructor inside *capsule* to *destructor*. + + Return ``0`` on success. Return nonzero and set an exception on failure. + ++ + .. c:function:: int PyCapsule_SetName(PyObject *capsule, const char *name) + + Set the name inside *capsule* to *name*. If non-*NULL*, the name must +@@ -142,6 +148,7 @@ Refer to :ref:`using-capsules` for more information on using these objects. + + Return ``0`` on success. Return nonzero and set an exception on failure. + ++ + .. c:function:: int PyCapsule_SetPointer(PyObject *capsule, void *pointer) + + Set the void pointer inside *capsule* to *pointer*. The pointer may not be +diff --git a/Doc/c-api/gcsupport.rst b/Doc/c-api/gcsupport.rst +index 9438feaeb1..18ecd071d7 100644 +--- a/Doc/c-api/gcsupport.rst ++++ b/Doc/c-api/gcsupport.rst +@@ -56,7 +56,7 @@ Constructors for container types must conform to two rules: + .. c:function:: TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize) + + Resize an object allocated by :c:func:`PyObject_NewVar`. Returns the +- resized object or *NULL* on failure. ++ resized object or *NULL* on failure. *op* must not be tracked by the collector yet. + + .. versionchanged:: 2.5 + This function used an :c:type:`int` type for *newsize*. This might +diff --git a/Doc/c-api/memory.rst b/Doc/c-api/memory.rst +index 258898d870..2b9fb7360b 100644 +--- a/Doc/c-api/memory.rst ++++ b/Doc/c-api/memory.rst +@@ -35,7 +35,7 @@ operate within the bounds of the private heap. + + It is important to understand that the management of the Python heap is + performed by the interpreter itself and that the user has no control over it, +-even if she regularly manipulates object pointers to memory blocks inside that ++even if they regularly manipulate object pointers to memory blocks inside that + heap. The allocation of heap space for Python objects and other internal + buffers is performed on demand by the Python memory manager through the Python/C + API functions listed in this document. +diff --git a/Doc/distributing/index.rst b/Doc/distributing/index.rst +index 82ecd2c1ef..b0dccb3db1 100644 +--- a/Doc/distributing/index.rst ++++ b/Doc/distributing/index.rst +@@ -31,7 +31,7 @@ installing other Python projects, refer to the + Key terms + ========= + +-* the `Python Packaging Index `__ is a public ++* the `Python Packaging Index `__ is a public + repository of open source licensed packages made available for use by + other Python users + * the `Python Packaging Authority +diff --git a/Doc/distutils/apiref.rst b/Doc/distutils/apiref.rst +index 18844dd767..34a3cb34af 100644 +--- a/Doc/distutils/apiref.rst ++++ b/Doc/distutils/apiref.rst +@@ -78,7 +78,7 @@ setup script). Indirectly provides the :class:`distutils.dist.Distribution` and + | | be built | :class:`distutils.core.Extension` | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *classifiers* | A list of categories for the | a list of strings; valid classifiers are listed on `PyPI | +- | | package | `_. | ++ | | package | `_. | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *distclass* | the :class:`Distribution` | a subclass of | + | | class to use | :class:`distutils.core.Distribution` | +diff --git a/Doc/distutils/builtdist.rst b/Doc/distutils/builtdist.rst +index 15ab3b3ed8..acd499a262 100644 +--- a/Doc/distutils/builtdist.rst ++++ b/Doc/distutils/builtdist.rst +@@ -21,7 +21,7 @@ specialty---writing code and creating source distributions---while an + intermediary species called *packagers* springs up to turn source distributions + into built distributions for as many platforms as there are packagers. + +-Of course, the module developer could be his own packager; or the packager could ++Of course, the module developer could be their own packager; or the packager could + be a volunteer "out there" somewhere who has access to a platform which the + original developer does not; or it could be software periodically grabbing new + source distributions and turning them into built distributions for as many +diff --git a/Doc/distutils/introduction.rst b/Doc/distutils/introduction.rst +index fc6184fa57..488619e3b3 100644 +--- a/Doc/distutils/introduction.rst ++++ b/Doc/distutils/introduction.rst +@@ -94,7 +94,7 @@ containing your setup script :file:`setup.py`, and your module :file:`foo.py`. + The archive file will be named :file:`foo-1.0.tar.gz` (or :file:`.zip`), and + will unpack into a directory :file:`foo-1.0`. + +-If an end-user wishes to install your :mod:`foo` module, all she has to do is ++If an end-user wishes to install your :mod:`foo` module, all they have to do is + download :file:`foo-1.0.tar.gz` (or :file:`.zip`), unpack it, and---from the + :file:`foo-1.0` directory---run :: + +@@ -193,8 +193,8 @@ modules using the Distutils: + module distribution + a collection of Python modules distributed together as a single downloadable + resource and meant to be installed *en masse*. Examples of some well-known +- module distributions are Numeric Python, PyXML, PIL (the Python Imaging +- Library), or mxBase. (This would be called a *package*, except that term is ++ module distributions are Numeric Python, PyXML, Pillow, ++ or mxBase. (This would be called a *package*, except that term is + already taken in the Python context: a single module distribution may contain + zero, one, or many Python packages.) + +diff --git a/Doc/distutils/packageindex.rst b/Doc/distutils/packageindex.rst +index 80875845f6..cd11f20df8 100644 +--- a/Doc/distutils/packageindex.rst ++++ b/Doc/distutils/packageindex.rst +@@ -248,4 +248,4 @@ without warnings does not guarantee that PyPI will convert the content + successfully. + + +-.. _Python Package Index (PyPI): https://pypi.python.org/pypi ++.. _Python Package Index (PyPI): https://pypi.org +diff --git a/Doc/distutils/setupscript.rst b/Doc/distutils/setupscript.rst +index 6b82c40546..92ab5732d2 100644 +--- a/Doc/distutils/setupscript.rst ++++ b/Doc/distutils/setupscript.rst +@@ -606,7 +606,7 @@ Notes: + (4) + These fields should not be used if your package is to be compatible with Python + versions prior to 2.2.3 or 2.3. The list is available from the `PyPI website +- `_. ++ `_. + + (5) + The ``long_description`` field is used by PyPI when you are +diff --git a/Doc/faq/design.rst b/Doc/faq/design.rst +index 15e4af57fe..8588daaa2f 100644 +--- a/Doc/faq/design.rst ++++ b/Doc/faq/design.rst +@@ -2,6 +2,11 @@ + Design and History FAQ + ====================== + ++.. only:: html ++ ++ .. contents:: ++ ++ + Why does Python use indentation for grouping of statements? + ----------------------------------------------------------- + +@@ -221,24 +226,25 @@ Python file objects support the iterator protocol, so you can now write simply:: + Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))? + ---------------------------------------------------------------------------------------------------------------- + +-The major reason is history. Functions were used for those operations that were +-generic for a group of types and which were intended to work even for objects +-that didn't have methods at all (e.g. tuples). It is also convenient to have a +-function that can readily be applied to an amorphous collection of objects when +-you use the functional features of Python (``map()``, ``zip()`` et al). ++As Guido said: + +-In fact, implementing ``len()``, ``max()``, ``min()`` as a built-in function is +-actually less code than implementing them as methods for each type. One can +-quibble about individual cases but it's a part of Python, and it's too late to +-make such fundamental changes now. The functions have to remain to avoid massive +-code breakage. ++ (a) For some operations, prefix notation just reads better than ++ postfix -- prefix (and infix!) operations have a long tradition in ++ mathematics which likes notations where the visuals help the ++ mathematician thinking about a problem. Compare the easy with which we ++ rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of ++ doing the same thing using a raw OO notation. + +-.. XXX talk about protocols? ++ (b) When I read code that says len(x) I *know* that it is asking for ++ the length of something. This tells me two things: the result is an ++ integer, and the argument is some kind of container. To the contrary, ++ when I read x.len(), I have to already know that x is some kind of ++ container implementing an interface or inheriting from a class that ++ has a standard len(). Witness the confusion we occasionally have when ++ a class that is not implementing a mapping has a get() or keys() ++ method, or something that isn't a file has a write() method. + +-.. note:: +- +- For string operations, Python has moved from external functions (the +- ``string`` module) to methods. However, ``len()`` is still a function. ++ -- https://mail.python.org/pipermail/python-3000/2006-November/004643.html + + + Why is join() a string method instead of a list or tuple method? +@@ -498,10 +504,10 @@ you can always change a list's elements. Only immutable elements can be used as + dictionary keys, and hence only tuples and not lists can be used as keys. + + +-How are lists implemented? +--------------------------- ++How are lists implemented in CPython? ++------------------------------------- + +-Python's lists are really variable-length arrays, not Lisp-style linked lists. ++CPython's lists are really variable-length arrays, not Lisp-style linked lists. + The implementation uses a contiguous array of references to other objects, and + keeps a pointer to this array and the array's length in a list head structure. + +@@ -514,10 +520,10 @@ when the array must be grown, some extra space is allocated so the next few + times don't require an actual resize. + + +-How are dictionaries implemented? +---------------------------------- ++How are dictionaries implemented in CPython? ++-------------------------------------------- + +-Python's dictionaries are implemented as resizable hash tables. Compared to ++CPython's dictionaries are implemented as resizable hash tables. Compared to + B-trees, this gives better performance for lookup (the most common operation by + far) under most circumstances, and the implementation is simpler. + +diff --git a/Doc/faq/general.rst b/Doc/faq/general.rst +index 35cad55c3a..eb1bd16b4b 100644 +--- a/Doc/faq/general.rst ++++ b/Doc/faq/general.rst +@@ -117,7 +117,7 @@ programming), software engineering (unit testing, logging, profiling, parsing + Python code), and operating system interfaces (system calls, filesystems, TCP/IP + sockets). Look at the table of contents for :ref:`library-index` to get an idea + of what's available. A wide variety of third-party extensions are also +-available. Consult `the Python Package Index `_ to ++available. Consult `the Python Package Index `_ to + find packages of interest to you. + + +diff --git a/Doc/faq/library.rst b/Doc/faq/library.rst +index d1b3efb4d7..a25946538e 100644 +--- a/Doc/faq/library.rst ++++ b/Doc/faq/library.rst +@@ -19,7 +19,7 @@ standard library module. (Eventually you'll learn what's in the standard + library and will be able to skip this step.) + + For third-party packages, search the `Python Package Index +-`_ or try `Google `_ or ++`_ or try `Google `_ or + another Web search engine. Searching for "Python" plus a keyword or two for + your topic of interest will usually find something helpful. + +@@ -585,7 +585,7 @@ substituted for standard input and output. You will have to use pseudo ttys + ("ptys") instead of pipes. Or you can use a Python interface to Don Libes' + "expect" library. A Python extension that interfaces to expect is called "expy" + and available from http://expectpy.sourceforge.net. A pure Python solution that +-works like expect is `pexpect `_. ++works like expect is `pexpect `_. + + + How do I access the serial (RS232) port? +diff --git a/Doc/glossary.rst b/Doc/glossary.rst +index cbd1237f8e..9e6bf233bb 100644 +--- a/Doc/glossary.rst ++++ b/Doc/glossary.rst +@@ -14,8 +14,9 @@ Glossary + + ``...`` + The default Python prompt of the interactive shell when entering code for +- an indented code block or within a pair of matching left and right +- delimiters (parentheses, square brackets or curly braces). ++ an indented code block, when within a pair of matching left and right ++ delimiters (parentheses, square brackets, curly braces or triple quotes), ++ or after specifying a decorator. + + 2to3 + A tool that tries to convert Python 2.x code to Python 3.x code by +@@ -296,7 +297,7 @@ Glossary + the :func:`next` function. Each :keyword:`yield` temporarily suspends + processing, remembering the location execution state (including local + variables and pending try-statements). When the generator resumes, it +- picks-up where it left-off (in contrast to functions which start fresh on ++ picks up where it left off (in contrast to functions which start fresh on + every invocation). + + .. index:: single: generator expression +@@ -457,7 +458,7 @@ Glossary + lambda + An anonymous inline function consisting of a single :term:`expression` + which is evaluated when the function is called. The syntax to create +- a lambda function is ``lambda [arguments]: expression`` ++ a lambda function is ``lambda [parameters]: expression`` + + LBYL + Look before you leap. This coding style explicitly tests for +@@ -474,7 +475,7 @@ Glossary + list + A built-in Python :term:`sequence`. Despite its name it is more akin + to an array in other languages than to a linked list since access to +- elements are O(1). ++ elements is O(1). + + list comprehension + A compact way to process all or part of the elements in a sequence and +@@ -625,6 +626,21 @@ Glossary + :ref:`the difference between arguments and parameters + `, and the :ref:`function` section. + ++ PEP ++ Python Enhancement Proposal. A PEP is a design document ++ providing information to the Python community, or describing a new ++ feature for Python or its processes or environment. PEPs should ++ provide a concise technical specification and a rationale for proposed ++ features. ++ ++ PEPs are intended to be the primary mechanisms for proposing major new ++ features, for collecting community input on an issue, and for documenting ++ the design decisions that have gone into Python. The PEP author is ++ responsible for building consensus within the community and documenting ++ dissenting opinions. ++ ++ See :pep:`1`. ++ + positional argument + See :term:`argument`. + +@@ -694,7 +710,7 @@ Glossary + + struct sequence + A tuple with named elements. Struct sequences expose an interface similiar +- to :term:`named tuple` in that elements can either be accessed either by ++ to :term:`named tuple` in that elements can be accessed either by + index or as an attribute. However, they do not have any of the named tuple + methods like :meth:`~collections.somenamedtuple._make` or + :meth:`~collections.somenamedtuple._asdict`. Examples of struct sequences +diff --git a/Doc/howto/doanddont.rst b/Doc/howto/doanddont.rst +index 98dbad192d..35e158370e 100644 +--- a/Doc/howto/doanddont.rst ++++ b/Doc/howto/doanddont.rst +@@ -285,7 +285,7 @@ There are also many useful built-in functions people seem not to be aware of + for some reason: :func:`min` and :func:`max` can find the minimum/maximum of + any sequence with comparable semantics, for example, yet many people write + their own :func:`max`/:func:`min`. Another highly useful function is +-:func:`reduce` which can be used to repeatly apply a binary operation to a ++:func:`reduce` which can be used to repeatedly apply a binary operation to a + sequence, reducing it to a single value. For example, compute a factorial + with a series of multiply operations:: + +diff --git a/Doc/howto/pyporting.rst b/Doc/howto/pyporting.rst +index 8562d23737..88b01779d2 100644 +--- a/Doc/howto/pyporting.rst ++++ b/Doc/howto/pyporting.rst +@@ -427,25 +427,25 @@ to make sure everything functions as expected in both versions of Python. + + + .. _2to3: https://docs.python.org/3/library/2to3.html +-.. _caniusepython3: https://pypi.python.org/pypi/caniusepython3 ++.. _caniusepython3: https://pypi.org/project/caniusepython3 + .. _cheat sheet: http://python-future.org/compatible_idioms.html +-.. _coverage.py: https://pypi.python.org/pypi/coverage ++.. _coverage.py: https://pypi.org/project/coverage + .. _Futurize: http://python-future.org/automatic_conversion.html + .. _importlib: https://docs.python.org/3/library/importlib.html#module-importlib +-.. _importlib2: https://pypi.python.org/pypi/importlib2 ++.. _importlib2: https://pypi.org/project/importlib2 + .. _Modernize: https://python-modernize.readthedocs.org/en/latest/ + .. _mypy: http://mypy-lang.org/ + .. _Porting to Python 3: http://python3porting.com/ +-.. _Pylint: https://pypi.python.org/pypi/pylint ++.. _Pylint: https://pypi.org/project/pylint + + .. _Python 3 Q & A: https://ncoghlan-devs-python-notes.readthedocs.org/en/latest/python3/questions_and_answers.html + + .. _pytype: https://github.com/google/pytype + .. _python-future: http://python-future.org/ + .. _python-porting: https://mail.python.org/mailman/listinfo/python-porting +-.. _six: https://pypi.python.org/pypi/six +-.. _tox: https://pypi.python.org/pypi/tox +-.. _trove classifier: https://pypi.python.org/pypi?%3Aaction=list_classifiers ++.. _six: https://pypi.org/project/six ++.. _tox: https://pypi.org/project/tox ++.. _trove classifier: https://pypi.org/classifiers + + .. _"What's New": https://docs.python.org/3/whatsnew/index.html + +diff --git a/Doc/howto/webservers.rst b/Doc/howto/webservers.rst +index a555083e32..5071a8a33c 100644 +--- a/Doc/howto/webservers.rst ++++ b/Doc/howto/webservers.rst +@@ -301,7 +301,7 @@ following WSGI-application:: + WSGIServer(app).run() + + This is a simple WSGI application, but you need to install `flup +-`_ first, as flup handles the low level ++`_ first, as flup handles the low level + FastCGI access. + + .. seealso:: +@@ -583,7 +583,7 @@ alternate storage mechanism. + helps with choosing a method for saving data + + * `SQLAlchemy `_, the most powerful OR-Mapper +- for Python, and `Elixir `_, which makes ++ for Python, and `Elixir `_, which makes + SQLAlchemy easier to use + + * `SQLObject `_, another popular OR-Mapper +diff --git a/Doc/includes/run-func.c b/Doc/includes/run-func.c +index 5a7df0d980..8276b0128f 100644 +--- a/Doc/includes/run-func.c ++++ b/Doc/includes/run-func.c +@@ -3,7 +3,7 @@ + int + main(int argc, char *argv[]) + { +- PyObject *pName, *pModule, *pDict, *pFunc; ++ PyObject *pName, *pModule, *pFunc; + PyObject *pArgs, *pValue; + int i; + +diff --git a/Doc/installing/index.rst b/Doc/installing/index.rst +index cbbb882406..9b89d083af 100644 +--- a/Doc/installing/index.rst ++++ b/Doc/installing/index.rst +@@ -39,9 +39,8 @@ Key terms + being installed system wide + * ``virtualenv`` is a third party tools for creating virtual environments, it + is defaults to installing ``pip`` into all created virtual environments. +-* the `Python Packaging Index `__ is a public +- repository of open source licensed packages made available for use by +- other Python users ++* the `Python Packaging Index `__ is a public repository of ++ open source licensed packages made available for use by other Python users + * the `Python Packaging Authority + `__ are the group of + developers and documentation authors responsible for the maintenance and +diff --git a/Doc/library/bz2.rst b/Doc/library/bz2.rst +index 71957ec06e..e764f39395 100644 +--- a/Doc/library/bz2.rst ++++ b/Doc/library/bz2.rst +@@ -74,7 +74,7 @@ Handling of compressed files is offered by the :class:`BZ2File` class. + input file, only the first stream will be accessible. If you require + support for multi-stream files, consider using the third-party + :mod:`bz2file` module (available from +- `PyPI `_). This module provides a ++ `PyPI `_). This module provides a + backport of Python 3.3's :class:`BZ2File` class, which does support + multi-stream files. + +diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst +index c88dd2318b..183da70603 100644 +--- a/Doc/library/contextlib.rst ++++ b/Doc/library/contextlib.rst +@@ -24,22 +24,28 @@ Functions provided: + function for :keyword:`with` statement context managers, without needing to + create a class or separate :meth:`__enter__` and :meth:`__exit__` methods. + +- A simple example (this is not recommended as a real way of generating HTML!):: ++ While many objects natively support use in with statements, sometimes a ++ resource needs to be managed that isn't a context manager in its own right, ++ and doesn't implement a ``close()`` method for use with ``contextlib.closing`` ++ ++ An abstract example would be the following to ensure correct resource ++ management:: + + from contextlib import contextmanager + + @contextmanager +- def tag(name): +- print "<%s>" % name +- yield +- print "" % name +- +- >>> with tag("h1"): +- ... print "foo" +- ... +-

+- foo +-

++ def managed_resource(*args, **kwds): ++ # Code to acquire resource, e.g.: ++ resource = acquire_resource(*args, **kwds) ++ try: ++ yield resource ++ finally: ++ # Code to release resource, e.g.: ++ release_resource(resource) ++ ++ >>> with managed_resource(timeout=3600) as resource: ++ ... # Resource is released at the end of this block, ++ ... # even if code in the block raises an exception + + The function being decorated must return a :term:`generator`-iterator when + called. This iterator must yield exactly one value, which will be bound to +diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst +index fedd370cf1..ad6b716e20 100644 +--- a/Doc/library/csv.rst ++++ b/Doc/library/csv.rst +@@ -453,8 +453,9 @@ read CSV files (assuming they support complex numbers at all). + + .. method:: csvwriter.writerows(rows) + +- Write all the *rows* parameters (a list of *row* objects as described above) to +- the writer's file object, formatted according to the current dialect. ++ Write all elements in *rows* (an iterable of *row* objects as described ++ above) to the writer's file object, formatted according to the current ++ dialect. + + Writer objects have the following public attribute: + +diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst +index b8d86e3b5a..d2c1c56386 100644 +--- a/Doc/library/datetime.rst ++++ b/Doc/library/datetime.rst +@@ -1566,7 +1566,7 @@ EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)). + + .. seealso:: + +- `pytz `_ ++ `pytz `_ + The standard library has no :class:`tzinfo` instances, but + there exists a third-party library which brings the *IANA timezone + database* (also known as the Olson database) to Python: *pytz*. +diff --git a/Doc/library/difflib.rst b/Doc/library/difflib.rst +index c6bf3ef677..01a3bfc2cd 100644 +--- a/Doc/library/difflib.rst ++++ b/Doc/library/difflib.rst +@@ -757,8 +757,10 @@ It is also contained in the Python source distribution, as + # we're passing these as arguments to the diff function + fromdate = time.ctime(os.stat(fromfile).st_mtime) + todate = time.ctime(os.stat(tofile).st_mtime) +- fromlines = open(fromfile, 'U').readlines() +- tolines = open(tofile, 'U').readlines() ++ with open(fromfile, 'U') as f: ++ fromlines = f.readlines() ++ with open(tofile, 'U') as f: ++ tolines = f.readlines() + + if options.u: + diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, +diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst +index 04b9b15386..e773ab8090 100644 +--- a/Doc/library/dis.rst ++++ b/Doc/library/dis.rst +@@ -107,7 +107,7 @@ The :mod:`dis` module defines the following functions and constants: + + .. data:: hasconst + +- Sequence of bytecodes that have a constant parameter. ++ Sequence of bytecodes that access a constant. + + + .. data:: hasfree +@@ -796,21 +796,25 @@ the more significant byte last. + + .. opcode:: RAISE_VARARGS (argc) + +- Raises an exception. *argc* indicates the number of parameters to the raise ++ Raises an exception. *argc* indicates the number of arguments to the raise + statement, ranging from 0 to 3. The handler will find the traceback as TOS2, + the parameter as TOS1, and the exception as TOS. + + + .. opcode:: CALL_FUNCTION (argc) + +- Calls a function. The low byte of *argc* indicates the number of positional +- parameters, the high byte the number of keyword parameters. On the stack, the +- opcode finds the keyword parameters first. For each keyword argument, the +- value is on top of the key. Below the keyword parameters, the positional +- parameters are on the stack, with the right-most parameter on top. Below the +- parameters, the function object to call is on the stack. Pops all function +- arguments, and the function itself off the stack, and pushes the return +- value. ++ Calls a callable object. The low byte of *argc* indicates the number of ++ positional arguments, the high byte the number of keyword arguments. ++ The stack contains keyword arguments on top (if any), then the positional ++ arguments below that (if any), then the callable object to call below that. ++ Each keyword argument is represented with two values on the stack: ++ the argument's name, and its value, with the argument's value above the ++ name on the stack. ++ The positional arguments are pushed in the order that they are passed in ++ to the callable object, with the right-most positional argument on top. ++ ``CALL_FUNCTION`` pops all arguments and the callable object off the stack, ++ calls the callable object with those arguments, and pushes the return value ++ returned by the callable object. + + + .. opcode:: MAKE_FUNCTION (argc) +@@ -847,24 +851,53 @@ the more significant byte last. + + .. opcode:: CALL_FUNCTION_VAR (argc) + +- Calls a function. *argc* is interpreted as in :opcode:`CALL_FUNCTION`. The +- top element on the stack contains the variable argument list, followed by +- keyword and positional arguments. ++ Calls a callable object, similarly to :opcode:`CALL_FUNCTION`. ++ *argc* represents the number of keyword and positional ++ arguments, identically to :opcode:`CALL_FUNCTION`. ++ The top of the stack contains an iterable object containing ++ additional positional arguments. ++ Below that are keyword arguments (if any), positional arguments (if any) ++ and a callable object, identically to :opcode:`CALL_FUNCTION`. ++ Before the callable object is called, the iterable object ++ is "unpacked" and its contents are appended to the positional ++ arguments passed in. ++ The iterable object is ignored when computing ++ the value of ``argc``. + + + .. opcode:: CALL_FUNCTION_KW (argc) + +- Calls a function. *argc* is interpreted as in :opcode:`CALL_FUNCTION`. The +- top element on the stack contains the keyword arguments dictionary, followed +- by explicit keyword and positional arguments. ++ Calls a callable object, similarly to :opcode:`CALL_FUNCTION`. ++ *argc* represents the number of keyword and positional ++ arguments, identically to :opcode:`CALL_FUNCTION`. ++ The top of the stack contains a mapping object containing additional keyword ++ arguments. ++ Below that are keyword arguments (if any), positional arguments (if any) ++ and a callable object, identically to :opcode:`CALL_FUNCTION`. ++ Before the callable is called, the mapping object at the top of the stack is ++ "unpacked" and its contents are appended to the keyword arguments passed in. ++ The mapping object at the top of the stack is ignored when computing ++ the value of ``argc``. + + + .. opcode:: CALL_FUNCTION_VAR_KW (argc) + +- Calls a function. *argc* is interpreted as in :opcode:`CALL_FUNCTION`. The +- top element on the stack contains the keyword arguments dictionary, followed +- by the variable-arguments tuple, followed by explicit keyword and positional +- arguments. ++ Calls a callable object, similarly to :opcode:`CALL_FUNCTION_VAR` and ++ :opcode:`CALL_FUNCTION_KW`. ++ *argc* represents the number of keyword and positional ++ arguments, identically to :opcode:`CALL_FUNCTION`. ++ The top of the stack contains a mapping object, as per ++ :opcode:`CALL_FUNCTION_KW`. ++ Below that is an iterable object, as per ++ :opcode:`CALL_FUNCTION_VAR`. ++ Below that are keyword arguments (if any), positional arguments (if any) ++ and a callable object, identically to :opcode:`CALL_FUNCTION`. ++ Before the callable is called, the mapping object and iterable object ++ are each "unpacked" and their contents passed in as keyword and ++ positional arguments respectively, ++ identically to :opcode:`CALL_FUNCTION_VAR` and :opcode:`CALL_FUNCTION_KW`. ++ The mapping object and iterable object are both ignored when computing ++ the value of ``argc``. + + + .. opcode:: HAVE_ARGUMENT () +diff --git a/Doc/library/distribution.rst b/Doc/library/distribution.rst +index b560999572..21dd18d94a 100644 +--- a/Doc/library/distribution.rst ++++ b/Doc/library/distribution.rst +@@ -4,7 +4,7 @@ Software Packaging and Distribution + + These libraries help you with publishing and installing Python software. + While these modules are designed to work in conjunction with the +-`Python Package Index `__, they can also be used ++`Python Package Index `__, they can also be used + with a local index server, or without any index server at all. + + .. toctree:: +diff --git a/Doc/library/exceptions.rst b/Doc/library/exceptions.rst +index fe14656008..8757c6cb44 100644 +--- a/Doc/library/exceptions.rst ++++ b/Doc/library/exceptions.rst +@@ -439,7 +439,7 @@ The following exceptions are the exceptions that are actually raised. + + .. exception:: ValueError + +- Raised when a built-in operation or function receives an argument that has the ++ Raised when an operation or function receives an argument that has the + right type but an inappropriate value, and the situation is not described by a + more precise exception such as :exc:`IndexError`. + +diff --git a/Doc/library/idle.rst b/Doc/library/idle.rst +index a461e51c21..3848231b61 100644 +--- a/Doc/library/idle.rst ++++ b/Doc/library/idle.rst +@@ -442,7 +442,7 @@ longer or disable the extension. + Calltips + ^^^^^^^^ + +-A calltip is shown when one types :kbd:`(` after the name of an *acccessible* ++A calltip is shown when one types :kbd:`(` after the name of an *accessible* + function. A name expression may include dots and subscripts. A calltip + remains until it is clicked, the cursor is moved out of the argument area, + or :kbd:`)` is typed. When the cursor is in the argument part of a definition, +diff --git a/Doc/library/index.rst b/Doc/library/index.rst +index 97cf3ea75c..31ca6df1d1 100644 +--- a/Doc/library/index.rst ++++ b/Doc/library/index.rst +@@ -30,7 +30,7 @@ optional components. + In addition to the standard library, there is a growing collection of + several thousand components (from individual programs and modules to + packages and entire application development frameworks), available from +-the `Python Package Index `_. ++the `Python Package Index `_. + + + .. toctree:: +diff --git a/Doc/library/io.rst b/Doc/library/io.rst +index b99324cdb3..dcdd01cd0a 100644 +--- a/Doc/library/io.rst ++++ b/Doc/library/io.rst +@@ -724,7 +724,7 @@ Text I/O + + .. versionadded:: 2.7 + +- .. method:: read(n) ++ .. method:: read(n=-1) + + Read and return at most *n* characters from the stream as a single + :class:`unicode`. If *n* is negative or ``None``, reads until EOF. +@@ -809,7 +809,7 @@ Text I/O + the given string. + + If *line_buffering* is ``True``, :meth:`flush` is implied when a call to +- write contains a newline character. ++ write contains a newline character or a carriage return. + + :class:`TextIOWrapper` provides one attribute in addition to those of + :class:`TextIOBase` and its parents: +diff --git a/Doc/library/logging.rst b/Doc/library/logging.rst +index 0f568aaa97..09cae18cfd 100644 +--- a/Doc/library/logging.rst ++++ b/Doc/library/logging.rst +@@ -949,26 +949,26 @@ functions. + +--------------+---------------------------------------------+ + | Format | Description | + +==============+=============================================+ +- | ``filename`` | Specifies that a FileHandler be created, | ++ | *filename* | Specifies that a FileHandler be created, | + | | using the specified filename, rather than a | + | | StreamHandler. | + +--------------+---------------------------------------------+ +- | ``filemode`` | Specifies the mode to open the file, if | +- | | filename is specified (if filemode is | +- | | unspecified, it defaults to 'a'). | ++ | *filemode* | If *filename* is specified, open the file | ++ | | in this mode. Defaults to ``'a'``. | + +--------------+---------------------------------------------+ +- | ``format`` | Use the specified format string for the | ++ | *format* | Use the specified format string for the | + | | handler. | + +--------------+---------------------------------------------+ +- | ``datefmt`` | Use the specified date/time format. | ++ | *datefmt* | Use the specified date/time format, as | ++ | | accepted by :func:`time.strftime`. | + +--------------+---------------------------------------------+ +- | ``level`` | Set the root logger level to the specified | +- | | level. | ++ | *level* | Set the root logger level to the specified | ++ | | :ref:`level `. | + +--------------+---------------------------------------------+ +- | ``stream`` | Use the specified stream to initialize the | ++ | *stream* | Use the specified stream to initialize the | + | | StreamHandler. Note that this argument is | +- | | incompatible with 'filename' - if both are | +- | | present, 'stream' is ignored. | ++ | | incompatible with *filename* - if both are | ++ | | present, *stream* is ignored. | + +--------------+---------------------------------------------+ + + +diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst +index 97a7b53667..2d8660aba9 100644 +--- a/Doc/library/multiprocessing.rst ++++ b/Doc/library/multiprocessing.rst +@@ -803,10 +803,13 @@ Miscellaneous + Connection Objects + ~~~~~~~~~~~~~~~~~~ + ++.. currentmodule:: None ++ + Connection objects allow the sending and receiving of picklable objects or + strings. They can be thought of as message oriented connected sockets. + +-Connection objects are usually created using :func:`Pipe` -- see also ++Connection objects are usually created using ++:func:`Pipe ` -- see also + :ref:`multiprocessing-listeners-clients`. + + .. class:: Connection +@@ -926,6 +929,8 @@ For example: + Synchronization primitives + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + ++.. currentmodule:: multiprocessing ++ + Generally synchronization primitives are not as necessary in a multiprocess + program as they are in a multithreaded program. See the documentation for + :mod:`threading` module. +@@ -1943,8 +1948,7 @@ Listeners and Clients + :synopsis: API for dealing with sockets. + + Usually message passing between processes is done using queues or by using +-:class:`~multiprocessing.Connection` objects returned by +-:func:`~multiprocessing.Pipe`. ++:class:`Connection` objects returned by :func:`~multiprocessing.Pipe`. + + However, the :mod:`multiprocessing.connection` module allows some extra + flexibility. It basically gives a high level message oriented API for dealing +@@ -1972,7 +1976,7 @@ authentication* using the :mod:`hmac` module. + .. function:: Client(address[, family[, authenticate[, authkey]]]) + + Attempt to set up a connection to the listener which is using address +- *address*, returning a :class:`~multiprocessing.Connection`. ++ *address*, returning a :class:`Connection`. + + The type of the connection is determined by *family* argument, but this can + generally be omitted since it can usually be inferred from the format of +@@ -2028,8 +2032,8 @@ authentication* using the :mod:`hmac` module. + .. method:: accept() + + Accept a connection on the bound socket or named pipe of the listener +- object and return a :class:`~multiprocessing.Connection` object. If +- authentication is attempted and fails, then ++ object and return a :class:`Connection` object. ++ If authentication is attempted and fails, then + :exc:`~multiprocessing.AuthenticationError` is raised. + + .. method:: close() +@@ -2050,11 +2054,24 @@ authentication* using the :mod:`hmac` module. + unavailable then it is ``None``. + + +-The module defines two exceptions: ++The module defines the following exceptions: ++ ++.. exception:: ProcessError ++ ++ The base class of all :mod:`multiprocessing` exceptions. ++ ++.. exception:: BufferTooShort ++ ++ Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied ++ buffer object is too small for the message read. + + .. exception:: AuthenticationError + +- Exception raised when there is an authentication error. ++ Raised when there is an authentication error. ++ ++.. exception:: TimeoutError ++ ++ Raised by methods with a timeout when the timeout expires. + + + **Examples** +@@ -2126,7 +2143,7 @@ an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address. + Authentication keys + ~~~~~~~~~~~~~~~~~~~ + +-When one uses :meth:`Connection.recv `, the ++When one uses :meth:`Connection.recv`, the + data received is automatically + unpickled. Unfortunately unpickling data from an untrusted source is a security + risk. Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module +diff --git a/Doc/library/optparse.rst b/Doc/library/optparse.rst +index 4af75a1014..627eb7dfca 100644 +--- a/Doc/library/optparse.rst ++++ b/Doc/library/optparse.rst +@@ -1679,7 +1679,7 @@ The callback function should raise :exc:`OptionValueError` if there are any + problems with the option or its argument(s). :mod:`optparse` catches this and + terminates the program, printing the error message you supply to stderr. Your + message should be clear, concise, accurate, and mention the option at fault. +-Otherwise, the user will have a hard time figuring out what he did wrong. ++Otherwise, the user will have a hard time figuring out what they did wrong. + + + .. _optparse-callback-example-1: +diff --git a/Doc/library/platform.rst b/Doc/library/platform.rst +index 9f64095270..3d0743bee2 100644 +--- a/Doc/library/platform.rst ++++ b/Doc/library/platform.rst +@@ -270,6 +270,10 @@ Unix Platforms + parameters. ``id`` is the item in parentheses after the version number. It + is usually the version codename. + ++ .. note:: ++ This function is deprecated since Python 3.5 and removed in Python 3.8. ++ See alternative like the `distro `_ package. ++ + .. versionadded:: 2.6 + + .. function:: libc_ver(executable=sys.executable, lib='', version='', chunksize=2048) +diff --git a/Doc/library/pprint.rst b/Doc/library/pprint.rst +index ffa27d4255..3f09b21d85 100644 +--- a/Doc/library/pprint.rst ++++ b/Doc/library/pprint.rst +@@ -234,4 +234,3 @@ parameters. + ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'], + ['cccccccccccccccccccc', 'dddddddddddddddddddd']] +- +diff --git a/Doc/library/profile.rst b/Doc/library/profile.rst +index 210e99c5ba..0926373edc 100644 +--- a/Doc/library/profile.rst ++++ b/Doc/library/profile.rst +@@ -333,11 +333,12 @@ Analysis of the profiler data is done using the :class:`~pstats.Stats` class. + corresponding version of :mod:`profile` or :mod:`cProfile`. To be specific, + there is *no* file compatibility guaranteed with future versions of this + profiler, and there is no compatibility with files produced by other +- profilers. If several files are provided, all the statistics for identical +- functions will be coalesced, so that an overall view of several processes can +- be considered in a single report. If additional files need to be combined +- with data in an existing :class:`~pstats.Stats` object, the +- :meth:`~pstats.Stats.add` method can be used. ++ profilers, or the same profiler run on a different operating system. If ++ several files are provided, all the statistics for identical functions will ++ be coalesced, so that an overall view of several processes can be considered ++ in a single report. If additional files need to be combined with data in an ++ existing :class:`~pstats.Stats` object, the :meth:`~pstats.Stats.add` method ++ can be used. + + Instead of reading the profile data from a file, a :class:`cProfile.Profile` + or :class:`profile.Profile` object can be used as the profile data source. +diff --git a/Doc/library/re.rst b/Doc/library/re.rst +index c424230e13..c708a29bbe 100644 +--- a/Doc/library/re.rst ++++ b/Doc/library/re.rst +@@ -35,7 +35,7 @@ fine-tuning parameters. + + .. seealso:: + +- The third-party `regex `_ module, ++ The third-party `regex `_ module, + which has an API compatible with the standard library :mod:`re` module, + but offers additional functionality and a more thorough Unicode support. + +@@ -1256,8 +1256,8 @@ Finding all Adverbs + ^^^^^^^^^^^^^^^^^^^ + + :func:`findall` matches *all* occurrences of a pattern, not just the first +-one as :func:`search` does. For example, if one was a writer and wanted to +-find all of the adverbs in some text, he or she might use :func:`findall` in ++one as :func:`search` does. For example, if a writer wanted to ++find all of the adverbs in some text, they might use :func:`findall` in + the following manner: + + >>> text = "He was carefully disguised but captured quickly by police." +@@ -1271,8 +1271,8 @@ Finding all Adverbs and their Positions + If one wants more information about all matches of a pattern than the matched + text, :func:`finditer` is useful as it provides instances of + :class:`MatchObject` instead of strings. Continuing with the previous example, +-if one was a writer who wanted to find all of the adverbs *and their positions* +-in some text, he or she would use :func:`finditer` in the following manner: ++if a writer wanted to find all of the adverbs *and their positions* ++in some text, they would use :func:`finditer` in the following manner: + + >>> text = "He was carefully disguised but captured quickly by police." + >>> for m in re.finditer(r"\w+ly", text): +diff --git a/Doc/library/site.rst b/Doc/library/site.rst +index ff7195dc23..1c2d63e448 100644 +--- a/Doc/library/site.rst ++++ b/Doc/library/site.rst +@@ -206,7 +206,7 @@ If it is called without arguments, it will print the contents of + If both options are given, user base and user site will be printed (always in + this order), separated by :data:`os.pathsep`. + +-If any option is given, the script will exit with one of these values: ``O`` if ++If any option is given, the script will exit with one of these values: ``0`` if + the user site-packages directory is enabled, ``1`` if it was disabled by the + user, ``2`` if it is disabled for security reasons or by an administrator, and a + value greater than 2 if there is an error. +diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst +index bd5dd14691..ce53e84513 100644 +--- a/Doc/library/sqlite3.rst ++++ b/Doc/library/sqlite3.rst +@@ -206,8 +206,8 @@ Module functions and constants + Registers a callable to convert a bytestring from the database into a custom + Python type. The callable will be invoked for all database values that are of + the type *typename*. Confer the parameter *detect_types* of the :func:`connect` +- function for how the type detection works. Note that the case of *typename* and +- the name of the type in your query must match! ++ function for how the type detection works. Note that *typename* and the name of ++ the type in your query are matched in case-insensitive manner. + + + .. function:: register_adapter(type, callable) +diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst +index 89b9ff3621..0421031772 100644 +--- a/Doc/library/ssl.rst ++++ b/Doc/library/ssl.rst +@@ -24,6 +24,9 @@ sockets, both client-side and server-side. This module uses the OpenSSL + library. It is available on all modern Unix systems, Windows, Mac OS X, and + probably additional platforms, as long as OpenSSL is installed on that platform. + ++.. versionchanged:: 2.7.13 ++ Updated to support linking with OpenSSL 1.1.0 ++ + .. note:: + + Some behavior may be platform dependent, since calls are made to the +@@ -211,7 +214,7 @@ instead. + + The *ciphers* parameter sets the available ciphers for this SSL object. + It should be a string in the `OpenSSL cipher list format +- `_. ++ `_. + + The parameter ``do_handshake_on_connect`` specifies whether to do the SSL + handshake automatically after doing a :meth:`socket.connect`, or whether the +@@ -1167,7 +1170,7 @@ to speed up repeated connections from the same clients. + + Set the available ciphers for sockets created with this context. + It should be a string in the `OpenSSL cipher list format +- `_. ++ `_. + If no cipher can be selected (because compile-time options or other + configuration forbids use of all the specified ciphers), an + :class:`SSLError` will be raised. +@@ -1392,7 +1395,7 @@ message with one of the parts, you can decrypt it with the other part, and + + A certificate contains information about two principals. It contains the name + of a *subject*, and the subject's public key. It also contains a statement by a +-second principal, the *issuer*, that the subject is who he claims to be, and ++second principal, the *issuer*, that the subject is who they claim to be, and + that this is indeed the subject's public key. The issuer's statement is signed + with the issuer's private key, which only the issuer knows. However, anyone can + verify the issuer's statement by finding the issuer's public key, decrypting the +@@ -1586,7 +1589,7 @@ Visual inspection shows that the certificate does identify the desired service + (('commonName', 'www.python.org'),)), + 'subjectAltName': (('DNS', 'www.python.org'), + ('DNS', 'python.org'), +- ('DNS', 'pypi.python.org'), ++ ('DNS', 'pypi.org'), + ('DNS', 'docs.python.org'), + ('DNS', 'testpypi.python.org'), + ('DNS', 'bugs.python.org'), +diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst +index e16bd77188..ff68738abc 100644 +--- a/Doc/library/stdtypes.rst ++++ b/Doc/library/stdtypes.rst +@@ -1381,7 +1381,7 @@ string functions based on regular expressions. + .. method:: str.upper() + + Return a copy of the string with all the cased characters [4]_ converted to +- uppercase. Note that ``str.upper().isupper()`` might be ``False`` if ``s`` ++ uppercase. Note that ``s.upper().isupper()`` might be ``False`` if ``s`` + contains uncased characters or if the Unicode category of the resulting + character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase). + +diff --git a/Doc/library/string.rst b/Doc/library/string.rst +index c2af446619..f8d41f9d67 100644 +--- a/Doc/library/string.rst ++++ b/Doc/library/string.rst +@@ -257,8 +257,9 @@ attribute using :func:`getattr`, while an expression of the form ``'[index]'`` + does an index lookup using :func:`__getitem__`. + + .. versionchanged:: 2.7 +- The positional argument specifiers can be omitted, so ``'{} {}'`` is +- equivalent to ``'{0} {1}'``. ++ The positional argument specifiers can be omitted for :meth:`str.format` and ++ :meth:`unicode.format`, so ``'{} {}'`` is equivalent to ``'{0} {1}'``, ++ ``u'{} {}'`` is equivalent to ``u'{0} {1}'``. + + Some simple format string examples:: + +@@ -463,10 +464,10 @@ The available presentation types for floating point and decimal values are: + | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an | + | | upper case 'E' as the separator character. | + +---------+----------------------------------------------------------+ +- | ``'f'`` | Fixed point. Displays the number as a fixed-point | +- | | number. The default precision is ``6``. | ++ | ``'f'`` | Fixed-point notation. Displays the number as a | ++ | | fixed-point number. The default precision is ``6``. | + +---------+----------------------------------------------------------+ +- | ``'F'`` | Fixed point. Same as ``'f'``. | ++ | ``'F'`` | Fixed point notation. Same as ``'f'``. | + +---------+----------------------------------------------------------+ + | ``'g'`` | General format. For a given precision ``p >= 1``, | + | | this rounds the number to ``p`` significant digits and | +diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst +index 284cf4465a..53a0161d4b 100644 +--- a/Doc/library/subprocess.rst ++++ b/Doc/library/subprocess.rst +@@ -32,7 +32,7 @@ functions can be found in the subprocess-replacements_ section. + + :pep:`324` -- PEP proposing the subprocess module + +-.. _subprocess32: https://pypi.python.org/pypi/subprocess32/ ++.. _subprocess32: https://pypi.org/project/subprocess32/ + + Using the :mod:`subprocess` Module + ---------------------------------- +diff --git a/Doc/library/sysconfig.rst b/Doc/library/sysconfig.rst +index e8fc09e995..3b58266d22 100644 +--- a/Doc/library/sysconfig.rst ++++ b/Doc/library/sysconfig.rst +@@ -83,7 +83,7 @@ Python currently supports seven schemes: + - *nt*: scheme for NT platforms like Windows. + - *nt_user*: scheme for NT platforms, when the *user* option is used. + - *os2*: scheme for OS/2 platforms. +-- *os2_home*: scheme for OS/2 patforms, when the *user* option is used. ++- *os2_home*: scheme for OS/2 platforms, when the *user* option is used. + + Each scheme is itself composed of a series of paths and each path has a unique + identifier. Python currently uses eight paths: +diff --git a/Doc/library/time.rst b/Doc/library/time.rst +index b2a9253cc8..48a01db752 100644 +--- a/Doc/library/time.rst ++++ b/Doc/library/time.rst +@@ -236,7 +236,7 @@ The module defines the following functions and data items: + argument. If *t* is not provided, the current time as returned by + :func:`localtime` is used. *format* must be a string. :exc:`ValueError` is + raised if any field in *t* is outside of the allowed range. :func:`strftime` +- returns a locale depedent byte string; the result may be converted to unicode ++ returns a locale dependent byte string; the result may be converted to unicode + by doing ``strftime().decode(locale.getlocale()[1])``. + + .. versionchanged:: 2.1 +diff --git a/Doc/library/tkinter.rst b/Doc/library/tkinter.rst +index ce5e63a717..3356e4ef23 100644 +--- a/Doc/library/tkinter.rst ++++ b/Doc/library/tkinter.rst +@@ -11,6 +11,11 @@ the Tk GUI toolkit. Both Tk and :mod:`Tkinter` are available on most Unix + platforms, as well as on Windows systems. (Tk itself is not part of Python; it + is maintained at ActiveState.) + ++Running ``python -m Tkinter`` from the command line should open a window ++demonstrating a simple Tk interface, letting you know that :mod:`Tkinter` is ++properly installed on your system, and also showing what version of Tcl/Tk is ++installed, so you can read the Tcl/Tk documentation specific to that version. ++ + .. note:: + + :mod:`Tkinter` has been renamed to :mod:`tkinter` in Python 3. The +@@ -19,6 +24,8 @@ is maintained at ActiveState.) + + .. seealso:: + ++ Tkinter documentation: ++ + `Python Tkinter Resources `_ + The Python Tkinter Topic Guide provides a great deal of information on using Tk + from Python and links to other sources of information on Tk. +@@ -32,17 +39,32 @@ is maintained at ActiveState.) + `Tkinter docs from effbot `_ + Online reference for tkinter supported by effbot.org. + +- `Tcl/Tk manual `_ +- Official manual for the latest tcl/tk version. +- +- `Programming Python `_ ++ `Programming Python `_ + Book by Mark Lutz, has excellent coverage of Tkinter. + +- `Modern Tkinter for Busy Python Developers `_ ++ `Modern Tkinter for Busy Python Developers `_ + Book by Mark Rozerman about building attractive and modern graphical user interfaces with Python and Tkinter. + + `Python and Tkinter Programming `_ +- The book by John Grayson (ISBN 1-884777-81-3). ++ Book by John Grayson (ISBN 1-884777-81-3). ++ ++ Tcl/Tk documentation: ++ ++ `Tk commands `_ ++ Most commands are available as :mod:`Tkinter` or :mod:`Tkinter.ttk` classes. ++ Change '8.6' to match the version of your Tcl/Tk installation. ++ ++ `Tcl/Tk recent man pages `_ ++ Recent Tcl/Tk manuals on www.tcl.tk. ++ ++ `ActiveState Tcl Home Page `_ ++ The Tk/Tcl development is largely taking place at ActiveState. ++ ++ `Tcl and the Tk Toolkit `_ ++ Book by John Ousterhout, the inventor of Tcl. ++ ++ `Practical Programming in Tcl and Tk `_ ++ Brent Welch's encyclopedic book. + + + Tkinter Modules +@@ -182,18 +204,6 @@ documentation that exists. Here are some hints: + when nothing else makes sense. + + +-.. seealso:: +- +- `ActiveState Tcl Home Page `_ +- The Tk/Tcl development is largely taking place at ActiveState. +- +- `Tcl and the Tk Toolkit `_ +- The book by John Ousterhout, the inventor of Tcl. +- +- `Practical Programming in Tcl and Tk `_ +- Brent Welch's encyclopedic book. +- +- + A Simple Hello World Program + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +@@ -801,12 +811,13 @@ Menu indexes (menu.invoke(), menu.entryconfig(), etc.) + Images + ^^^^^^ + +-Bitmap/Pixelmap images can be created through the subclasses of +-:class:`Tkinter.Image`: ++Images of different formats can be created through the corresponding subclass ++of :class:`Tkinter.Image`: + +-* :class:`BitmapImage` can be used for X11 bitmap data. ++* :class:`BitmapImage` for images in XBM format. + +-* :class:`PhotoImage` can be used for GIF and PPM/PGM color bitmaps. ++* :class:`PhotoImage` for images in PGM, PPM, GIF and PNG formats. The latter ++ is supported starting with Tk 8.6. + + Either type of image is created through either the ``file`` or the ``data`` + option (other options are available as well). +@@ -817,6 +828,10 @@ reference to the image. When the last Python reference to the image object is + deleted, the image data is deleted as well, and Tk will display an empty box + wherever the image was used. + ++.. seealso:: ++ ++ The `Pillow `_ package adds support for ++ formats such as BMP, JPEG, TIFF, and WebP, among others. + + .. _tkinter-file-handlers: + +diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst +index b36126e1cc..06368fcb3d 100644 +--- a/Doc/library/unittest.rst ++++ b/Doc/library/unittest.rst +@@ -78,7 +78,7 @@ need to derive from a specific class. + Module :mod:`doctest` + Another test-support module with a very different flavor. + +- `unittest2: A backport of new unittest features for Python 2.4-2.6 `_ ++ `unittest2: A backport of new unittest features for Python 2.4-2.6 `_ + Many new features were added to unittest in Python 2.7, including test + discovery. unittest2 allows you to use these features with earlier + versions of Python. +@@ -730,7 +730,7 @@ Test cases + + .. method:: setUpClass() + +- A class method called before tests in an individual class run. ++ A class method called before tests in an individual class are run. + ``setUpClass`` is called with the class as the only argument + and must be decorated as a :func:`classmethod`:: + +diff --git a/Doc/library/urllib.rst b/Doc/library/urllib.rst +index 2a5ea717f0..c24f4375e9 100644 +--- a/Doc/library/urllib.rst ++++ b/Doc/library/urllib.rst +@@ -166,9 +166,9 @@ High-level interface + + The second argument, if present, specifies the file location to copy to (if + absent, the location will be a tempfile with a generated name). The third +- argument, if present, is a hook function that will be called once on ++ argument, if present, is a callable that will be called once on + establishment of the network connection and once after each block read +- thereafter. The hook will be passed three arguments; a count of blocks ++ thereafter. The callable will be passed three arguments; a count of blocks + transferred so far, a block size in bytes, and the total size of the file. The + third argument may be ``-1`` on older FTP servers which do not return a file + size in response to a retrieval request. +diff --git a/Doc/library/uuid.rst b/Doc/library/uuid.rst +index bc69b5f025..d2808cdfad 100644 +--- a/Doc/library/uuid.rst ++++ b/Doc/library/uuid.rst +@@ -23,12 +23,13 @@ random UUID. + .. class:: UUID([hex[, bytes[, bytes_le[, fields[, int[, version]]]]]]) + + Create a UUID from either a string of 32 hexadecimal digits, a string of 16 +- bytes as the *bytes* argument, a string of 16 bytes in little-endian order as +- the *bytes_le* argument, a tuple of six integers (32-bit *time_low*, 16-bit +- *time_mid*, 16-bit *time_hi_version*, 8-bit *clock_seq_hi_variant*, 8-bit +- *clock_seq_low*, 48-bit *node*) as the *fields* argument, or a single 128-bit +- integer as the *int* argument. When a string of hex digits is given, curly +- braces, hyphens, and a URN prefix are all optional. For example, these ++ bytes in big-endian order as the *bytes* argument, a string of 16 bytes in ++ little-endian order as the *bytes_le* argument, a tuple of six integers ++ (32-bit *time_low*, 16-bit *time_mid*, 16-bit *time_hi_version*, ++ 8-bit *clock_seq_hi_variant*, 8-bit *clock_seq_low*, 48-bit *node*) as the ++ *fields* argument, or a single 128-bit integer as the *int* argument. ++ When a string of hex digits is given, curly braces, hyphens, ++ and a URN prefix are all optional. For example, these + expressions all yield the same UUID:: + + UUID('{12345678-1234-5678-1234-567812345678}') +diff --git a/Doc/library/xml.rst b/Doc/library/xml.rst +index a8f20cdbf4..b107c29c64 100644 +--- a/Doc/library/xml.rst ++++ b/Doc/library/xml.rst +@@ -129,8 +129,8 @@ break backward compatibility. After all inline DTD and entity expansion are + well-defined XML features. + + +-.. _defusedxml: https://pypi.python.org/pypi/defusedxml/ +-.. _defusedexpat: https://pypi.python.org/pypi/defusedexpat/ ++.. _defusedxml: https://pypi.org/project/defusedxml/ ++.. _defusedexpat: https://pypi.org/project/defusedexpat/ + .. _Billion Laughs: https://en.wikipedia.org/wiki/Billion_laughs + .. _ZIP bomb: https://en.wikipedia.org/wiki/Zip_bomb + .. _DTD: https://en.wikipedia.org/wiki/Document_type_definition +diff --git a/Doc/reference/compound_stmts.rst b/Doc/reference/compound_stmts.rst +index 66ae5300b0..92ce3cdeed 100644 +--- a/Doc/reference/compound_stmts.rst ++++ b/Doc/reference/compound_stmts.rst +@@ -185,7 +185,7 @@ effect of Pascal's ``for i := a to b do``; e.g., ``range(3)`` returns the list + single: mutable sequence; loop over + + There is a subtlety when the sequence is being modified by the loop (this can +- only occur for mutable sequences, i.e. lists). An internal counter is used to ++ only occur for mutable sequences, e.g. lists). An internal counter is used to + keep track of which item is used next, and this is incremented on each + iteration. When this counter has reached the length of the sequence the loop + terminates. This means that if the suite deletes the current (or a previous) +diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst +index 8556fa810f..6afc867342 100644 +--- a/Doc/reference/expressions.rst ++++ b/Doc/reference/expressions.rst +@@ -581,7 +581,7 @@ whose value is one of the keys of the mapping, and the subscription selects the + value in the mapping that corresponds to that key. (The expression list is a + tuple except if it has exactly one item.) + +-If the primary is a sequence, the expression (list) must evaluate to a plain ++If the primary is a sequence, the expression list must evaluate to a plain + integer. If this value is negative, the length of the sequence is added to it + (so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value + must be a nonnegative integer less than the number of items in the sequence, and +@@ -1390,10 +1390,10 @@ Lambdas + + Lambda expressions (sometimes called lambda forms) have the same syntactic position as + expressions. They are a shorthand to create anonymous functions; the expression +-``lambda arguments: expression`` yields a function object. The unnamed object ++``lambda parameters: expression`` yields a function object. The unnamed object + behaves like a function object defined with :: + +- def name(arguments): ++ def (parameters): + return expression + + See section :ref:`function` for the syntax of parameter lists. Note that +diff --git a/Doc/reference/lexical_analysis.rst b/Doc/reference/lexical_analysis.rst +index 9f69ef7c8d..435dfc5d15 100644 +--- a/Doc/reference/lexical_analysis.rst ++++ b/Doc/reference/lexical_analysis.rst +@@ -73,11 +73,12 @@ Physical lines + -------------- + + A physical line is a sequence of characters terminated by an end-of-line +-sequence. In source files, any of the standard platform line termination +-sequences can be used - the Unix form using ASCII LF (linefeed), the Windows +-form using the ASCII sequence CR LF (return followed by linefeed), or the old +-Macintosh form using the ASCII CR (return) character. All of these forms can be +-used equally, regardless of platform. ++sequence. In source files and strings, any of the standard platform line ++termination sequences can be used - the Unix form using ASCII LF (linefeed), ++the Windows form using the ASCII sequence CR LF (return followed by linefeed), ++or the old Macintosh form using the ASCII CR (return) character. All of these ++forms can be used equally, regardless of platform. The end of input also serves ++as an implicit terminator for the final physical line. + + When embedding Python, source code strings should be passed to Python APIs using + the standard C conventions for newline characters (the ``\n`` character, +diff --git a/Doc/reference/toplevel_components.rst b/Doc/reference/toplevel_components.rst +index 304abac7cd..44196f746c 100644 +--- a/Doc/reference/toplevel_components.rst ++++ b/Doc/reference/toplevel_components.rst +@@ -51,11 +51,11 @@ a complete program; each statement is executed in the namespace of + single: command line + single: standard input + +-Under Unix, a complete program can be passed to the interpreter in three forms: +-with the :option:`-c` *string* command line option, as a file passed as the +-first command line argument, or as standard input. If the file or standard input +-is a tty device, the interpreter enters interactive mode; otherwise, it executes +-the file as a complete program. ++A complete program can be passed to the interpreter ++in three forms: with the :option:`-c` *string* command line option, as a file ++passed as the first command line argument, or as standard input. If the file ++or standard input is a tty device, the interpreter enters interactive mode; ++otherwise, it executes the file as a complete program. + + + .. _file-input: +diff --git a/Doc/tools/extensions/pyspecific.py b/Doc/tools/extensions/pyspecific.py +index 7bbd580d20..8c45274bb2 100644 +--- a/Doc/tools/extensions/pyspecific.py ++++ b/Doc/tools/extensions/pyspecific.py +@@ -15,9 +15,11 @@ SOURCE_URI = 'https://github.com/python/cpython/tree/2.7/%s' + from docutils import nodes, utils + from docutils.parsers.rst import Directive + ++from sphinx.util import status_iterator + from sphinx.util.nodes import split_explicit_title + from sphinx.writers.html import HTMLTranslator + from sphinx.writers.latex import LaTeXTranslator ++from sphinx.writers.text import TextTranslator + + # monkey-patch reST parser to disable alphabetic and roman enumerated lists + from docutils.parsers.rst.states import Body +@@ -158,8 +160,11 @@ from sphinx.writers.text import TextWriter + class PydocTopicsBuilder(Builder): + name = 'pydoc-topics' + ++ default_translator_class = TextTranslator ++ + def init(self): + self.topics = {} ++ self.secnumbers = {} + + def get_outdated_docs(self): + return 'all pydoc topics' +@@ -169,9 +174,9 @@ class PydocTopicsBuilder(Builder): + + def write(self, *ignored): + writer = TextWriter(self) +- for label in self.status_iterator(pydoc_topic_labels, +- 'building topics... ', +- length=len(pydoc_topic_labels)): ++ for label in status_iterator(pydoc_topic_labels, ++ 'building topics... ', ++ length=len(pydoc_topic_labels)): + if label not in self.env.domaindata['std']['labels']: + self.warn('label %r not in documentation' % label) + continue +diff --git a/Doc/tools/static/switchers.js b/Doc/tools/static/switchers.js +index 8e0c5ea009..2c051eb077 100644 +--- a/Doc/tools/static/switchers.js ++++ b/Doc/tools/static/switchers.js +@@ -11,7 +11,7 @@ + + var all_versions = { + '3.8': 'dev (3.8)', +- '3.7': 'pre (3.7)', ++ '3.7': '3.7', + '3.6': '3.6', + '3.5': '3.5', + '2.7': '2.7', +diff --git a/Doc/tools/templates/indexsidebar.html b/Doc/tools/templates/indexsidebar.html +index ddd8d75432..d6b054e876 100644 +--- a/Doc/tools/templates/indexsidebar.html ++++ b/Doc/tools/templates/indexsidebar.html +@@ -3,9 +3,9 @@ +

{% trans %}Docs for other versions{% endtrans %}

+ + +diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst +index 7f45c7632d..1058b77dd5 100644 +--- a/Doc/tutorial/classes.rst ++++ b/Doc/tutorial/classes.rst +@@ -328,8 +328,8 @@ the corresponding function with an argument list that is created by inserting + the method's object before the first argument. + + If you still don't understand how methods work, a look at the implementation can +-perhaps clarify matters. When an instance attribute is referenced that isn't a +-data attribute, its class is searched. If the name denotes a valid class ++perhaps clarify matters. When a non-data attribute of an instance is ++referenced, the instance's class is searched. If the name denotes a valid class + attribute that is a function object, a method object is created by packing + (pointers to) the instance object and the function object just found together in + an abstract object: this is the method object. When the method object is called +diff --git a/Doc/tutorial/interpreter.rst b/Doc/tutorial/interpreter.rst +index 6c8609faba..b727be00ab 100644 +--- a/Doc/tutorial/interpreter.rst ++++ b/Doc/tutorial/interpreter.rst +@@ -137,12 +137,12 @@ where *encoding* is one of the valid :mod:`codecs` supported by Python. + For example, to declare that Windows-1252 encoding is to be used, the first + line of your source code file should be:: + +- # -*- coding: cp-1252 -*- ++ # -*- coding: cp1252 -*- + + One exception to the *first line* rule is when the source code starts with a + :ref:`UNIX "shebang" line `. In this case, the encoding + declaration should be added as the second line of the file. For example:: + + #!/usr/bin/env python +- # -*- coding: cp-1252 -*- ++ # -*- coding: cp1252 -*- + +diff --git a/Doc/tutorial/introduction.rst b/Doc/tutorial/introduction.rst +index be9aa83474..2ff776e8bd 100644 +--- a/Doc/tutorial/introduction.rst ++++ b/Doc/tutorial/introduction.rst +@@ -149,12 +149,12 @@ to escape quotes:: + "doesn't" + >>> "doesn't" # ...or use double quotes instead + "doesn't" +- >>> '"Yes," he said.' +- '"Yes," he said.' +- >>> "\"Yes,\" he said." +- '"Yes," he said.' +- >>> '"Isn\'t," she said.' +- '"Isn\'t," she said.' ++ >>> '"Yes," they said.' ++ '"Yes," they said.' ++ >>> "\"Yes,\" they said." ++ '"Yes," they said.' ++ >>> '"Isn\'t," they said.' ++ '"Isn\'t," they said.' + + In the interactive interpreter, the output string is enclosed in quotes and + special characters are escaped with backslashes. While this might sometimes +@@ -165,10 +165,10 @@ enclosed in single quotes. The :keyword:`print` statement produces a more + readable output, by omitting the enclosing quotes and by printing escaped + and special characters:: + +- >>> '"Isn\'t," she said.' +- '"Isn\'t," she said.' +- >>> print '"Isn\'t," she said.' +- "Isn't," she said. ++ >>> '"Isn\'t," they said.' ++ '"Isn\'t," they said.' ++ >>> print '"Isn\'t," they said.' ++ "Isn't," they said. + >>> s = 'First line.\nSecond line.' # \n means newline + >>> s # without print, \n is included in the output + 'First line.\nSecond line.' +diff --git a/Doc/tutorial/modules.rst b/Doc/tutorial/modules.rst +index ec3bd9c53d..042d23306b 100644 +--- a/Doc/tutorial/modules.rst ++++ b/Doc/tutorial/modules.rst +@@ -377,7 +377,7 @@ module names". For example, the module name :mod:`A.B` designates a submodule + named ``B`` in a package named ``A``. Just like the use of modules saves the + authors of different modules from having to worry about each other's global + variable names, the use of dotted module names saves the authors of multi-module +-packages like NumPy or the Python Imaging Library from having to worry about ++packages like NumPy or Pillow from having to worry about + each other's module names. + + Suppose you want to design a collection of modules (a "package") for the uniform +diff --git a/Doc/tutorial/whatnow.rst b/Doc/tutorial/whatnow.rst +index 89dfa6a157..f6ce4f4617 100644 +--- a/Doc/tutorial/whatnow.rst ++++ b/Doc/tutorial/whatnow.rst +@@ -38,7 +38,7 @@ More Python resources: + + * https://docs.python.org: Fast access to Python's documentation. + +-* https://pypi.python.org/pypi: The Python Package Index, previously also nicknamed ++* https://pypi.org: The Python Package Index, previously also nicknamed + the Cheese Shop, is an index of user-created Python modules that are available + for download. Once you begin releasing code, you can register it here so that + others can find it. +diff --git a/Doc/using/windows.rst b/Doc/using/windows.rst +index f597476e33..778b8843f2 100644 +--- a/Doc/using/windows.rst ++++ b/Doc/using/windows.rst +@@ -242,7 +242,7 @@ The Windows-specific standard modules are documented in + PyWin32 + ------- + +-The `PyWin32 `_ module by Mark Hammond ++The `PyWin32 `_ module by Mark Hammond + is a collection of modules for advanced Windows-specific support. This includes + utilities for: + +diff --git a/Doc/whatsnew/2.3.rst b/Doc/whatsnew/2.3.rst +index 838ca38f31..1ef2cb5f98 100644 +--- a/Doc/whatsnew/2.3.rst ++++ b/Doc/whatsnew/2.3.rst +@@ -659,7 +659,7 @@ The heart of the catalog is the new Distutils :command:`register` command. + Running ``python setup.py register`` will collect the metadata describing a + package, such as its name, version, maintainer, description, &c., and send it to + a central catalog server. The resulting catalog is available from +-https://pypi.python.org/pypi. ++https://pypi.org. + + To make the catalog a bit more useful, a new optional *classifiers* keyword + argument has been added to the Distutils :func:`setup` function. A list of +diff --git a/Doc/whatsnew/2.5.rst b/Doc/whatsnew/2.5.rst +index d2395e7097..6400bb1086 100644 +--- a/Doc/whatsnew/2.5.rst ++++ b/Doc/whatsnew/2.5.rst +@@ -229,7 +229,7 @@ required packages. :: + ) + + Another new enhancement to the Python package index at +-https://pypi.python.org is storing source and binary archives for a ++https://pypi.org is storing source and binary archives for a + package. The new :command:`upload` Distutils command will upload a package to + the repository. + +diff --git a/Doc/whatsnew/2.7.rst b/Doc/whatsnew/2.7.rst +index 53333ebf7c..992658e8ba 100644 +--- a/Doc/whatsnew/2.7.rst ++++ b/Doc/whatsnew/2.7.rst +@@ -1218,11 +1218,6 @@ changes, or look through the Subversion logs for all the details. + created some new files that should be included. + (Fixed by Tarek Ziadé; :issue:`8688`.) + +- The ``upload`` command now longer tries to change CR end-of-line characters +- to CRLF. This fixes a corruption issue with sdists that ended with a byte +- equivalent to CR. +- (Contributed by Bo Bayles in :issue:`32304`.) +- + * The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag + will now ignore the name of the module containing the exception + being tested. (Patch by Lennart Regebro; :issue:`7490`.) +@@ -1535,7 +1530,7 @@ changes, or look through the Subversion logs for all the details. + *ciphers* argument that's a string listing the encryption algorithms + to be allowed; the format of the string is described + `in the OpenSSL documentation +- `__. ++ `__. + (Added by Antoine Pitrou; :issue:`8322`.) + + Another change makes the extension load all of OpenSSL's ciphers and +@@ -1790,7 +1785,7 @@ wish to read the Tcl/Tk manual page describing the + Ttk theme engine, available at + https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some + screenshots of the Python/Ttk code in use are at +-http://code.google.com/p/python-ttk/wiki/Screenshots. ++https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki. + + The :mod:`ttk` module was written by Guilherme Polo and added in + :issue:`2983`. An alternate version called ``Tile.py``, written by +@@ -1809,12 +1804,12 @@ new features were added. Most of these features were implemented + by Michael Foord, unless otherwise noted. The enhanced version of + the module is downloadable separately for use with Python versions 2.4 to 2.6, + packaged as the :mod:`unittest2` package, from +-https://pypi.python.org/pypi/unittest2. ++https://pypi.org/project/unittest2. + + When used from the command line, the module can automatically discover + tests. It's not as fancy as `py.test `__ or +-`nose `__, but provides a simple way +-to run tests kept within a set of package directories. For example, ++`nose `__, but provides a ++simple way to run tests kept within a set of package directories. For example, + the following command will search the :file:`test/` subdirectory for + any importable test files named ``test*.py``:: + +@@ -2728,6 +2723,39 @@ For cases where the connection establishment code can't be modified, but the + overall application can be, the new :func:`ssl._https_verify_certificates` + function can be used to adjust the default behaviour at runtime. + ++ ++New ``make regen-all`` build target ++----------------------------------- ++ ++To simplify cross-compilation, and to ensure that CPython can reliably be ++compiled without requiring an existing version of Python to already be ++available, the autotools-based build system no longer attempts to implicitly ++recompile generated files based on file modification times. ++ ++Instead, a new ``make regen-all`` command has been added to force regeneration ++of these files when desired (e.g. after an initial version of Python has ++already been built based on the pregenerated versions). ++ ++More selective regeneration targets are also defined - see ++:source:`Makefile.pre.in` for details. ++ ++(Contributed by Victor Stinner in :issue:`23404`.) ++ ++.. versionadded:: 2.7.14 ++ ++ ++Removal of ``make touch`` build target ++-------------------------------------- ++ ++The ``make touch`` build target previously used to request implicit regeneration ++of generated files by updating their modification times has been removed. ++ ++It has been replaced by the new ``make regen-all`` target. ++ ++(Contributed by Victor Stinner in :issue:`23404`.) ++ ++.. versionchanged:: 2.7.14 ++ + .. ====================================================================== + + .. _acks27: +diff --git a/Include/errcode.h b/Include/errcode.h +index becec80c8a..5c5a0f7fa3 100644 +--- a/Include/errcode.h ++++ b/Include/errcode.h +@@ -29,6 +29,7 @@ extern "C" { + #define E_EOFS 23 /* EOF in triple-quoted string */ + #define E_EOLS 24 /* EOL in single-quoted string */ + #define E_LINECONT 25 /* Unexpected characters after a line continuation */ ++#define E_IO 26 /* I/O error */ + + #ifdef __cplusplus + } +diff --git a/Include/grammar.h b/Include/grammar.h +index 8426da30d9..decf2e6126 100644 +--- a/Include/grammar.h ++++ b/Include/grammar.h +@@ -69,6 +69,7 @@ typedef struct { + /* FUNCTIONS */ + + grammar *newgrammar(int start); ++void freegrammar(grammar *g); + dfa *adddfa(grammar *g, int type, char *name); + int addstate(dfa *d); + void addarc(dfa *d, int from, int to, int lbl); +diff --git a/Include/intobject.h b/Include/intobject.h +index 59d061629e..d1985748b3 100644 +--- a/Include/intobject.h ++++ b/Include/intobject.h +@@ -31,6 +31,9 @@ PyAPI_DATA(PyTypeObject) PyInt_Type; + PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_INT_SUBCLASS) + #define PyInt_CheckExact(op) (Py_TYPE(op) == &PyInt_Type) + ++#define _PyAnyInt_Check(op) (PyInt_Check(op) || PyLong_Check(op)) ++#define _PyAnyInt_CheckExact(op) (PyInt_CheckExact(op) || PyLong_CheckExact(op)) ++ + PyAPI_FUNC(PyObject *) PyInt_FromString(char*, char**, int); + #ifdef Py_USING_UNICODE + PyAPI_FUNC(PyObject *) PyInt_FromUnicode(Py_UNICODE*, Py_ssize_t, int); +diff --git a/Include/patchlevel.h b/Include/patchlevel.h +index 99e837024a..8a04a90f9a 100644 +--- a/Include/patchlevel.h ++++ b/Include/patchlevel.h +@@ -27,7 +27,7 @@ + #define PY_RELEASE_SERIAL 0 + + /* Version as a string */ +-#define PY_VERSION "2.7.15" ++#define PY_VERSION "2.7.15+" + /*--end constants--*/ + + /* Subversion Revision number of this file (not of the repository). Empty +diff --git a/Include/pyexpat.h b/Include/pyexpat.h +index 5340ef5fa3..3fc5fa54da 100644 +--- a/Include/pyexpat.h ++++ b/Include/pyexpat.h +@@ -3,7 +3,7 @@ + + /* note: you must import expat.h before importing this module! */ + +-#define PyExpat_CAPI_MAGIC "pyexpat.expat_CAPI 1.0" ++#define PyExpat_CAPI_MAGIC "pyexpat.expat_CAPI 1.1" + #define PyExpat_CAPSULE_NAME "pyexpat.expat_CAPI" + + struct PyExpat_CAPI +@@ -43,6 +43,8 @@ struct PyExpat_CAPI + XML_Parser parser, XML_UnknownEncodingHandler handler, + void *encodingHandlerData); + void (*SetUserData)(XML_Parser parser, void *userData); ++ /* might be none for expat < 2.1.0 */ ++ int (*SetHashSalt)(XML_Parser parser, unsigned long hash_salt); + /* always add new stuff to the end! */ + }; + +diff --git a/Lib/_pyio.py b/Lib/_pyio.py +index f022a4e88b..98c2d58d0d 100644 +--- a/Lib/_pyio.py ++++ b/Lib/_pyio.py +@@ -1619,6 +1619,7 @@ class TextIOWrapper(TextIOBase): + self.buffer.write(b) + if self._line_buffering and (haslf or "\r" in s): + self.flush() ++ self._set_decoded_chars('') + self._snapshot = None + if self._decoder: + self._decoder.reset() +diff --git a/Lib/argparse.py b/Lib/argparse.py +index 1b233b85d2..d0004864d1 100644 +--- a/Lib/argparse.py ++++ b/Lib/argparse.py +@@ -324,7 +324,11 @@ class HelpFormatter(object): + if len(prefix) + len(usage) > text_width: + + # break usage into wrappable parts +- part_regexp = r'\(.*?\)+|\[.*?\]+|\S+' ++ part_regexp = ( ++ r'\(.*?\)+(?=\s|$)|' ++ r'\[.*?\]+(?=\s|$)|' ++ r'\S+' ++ ) + opt_usage = format(optionals, groups) + pos_usage = format(positionals, groups) + opt_parts = _re.findall(part_regexp, opt_usage) +diff --git a/Lib/bsddb/test/test_associate.py b/Lib/bsddb/test/test_associate.py +index f0eadaaf66..4a8d2aed99 100644 +--- a/Lib/bsddb/test/test_associate.py ++++ b/Lib/bsddb/test/test_associate.py +@@ -114,6 +114,22 @@ class AssociateErrorTestCase(unittest.TestCase): + dupDB.close() + self.fail("DBError exception was expected") + ++ @unittest.skipUnless(db.version() >= (4, 6), 'Needs 4.6+') ++ def test_associateListError(self): ++ db1 = db.DB(self.env) ++ db1.open('bad.db', "a.db", db.DB_BTREE, db.DB_CREATE) ++ db2 = db.DB(self.env) ++ db2.open('bad.db', "b.db", db.DB_BTREE, db.DB_CREATE) ++ ++ db1.associate(db2, lambda a, b: [0]) ++ ++ msg = "TypeError: The list returned by DB->associate callback" \ ++ " should be a list of strings." ++ with test_support.captured_output("stderr") as s: ++ db1.put("0", "1") ++ db1.close() ++ db2.close() ++ self.assertEquals(s.getvalue().strip(), msg) + + + #---------------------------------------------------------------------- +diff --git a/Lib/cProfile.py b/Lib/cProfile.py +index b2efd047d3..d3770946db 100755 +--- a/Lib/cProfile.py ++++ b/Lib/cProfile.py +@@ -64,11 +64,11 @@ def help(): + # ____________________________________________________________ + + class Profile(_lsprof.Profiler): +- """Profile(custom_timer=None, time_unit=None, subcalls=True, builtins=True) ++ """Profile(timer=None, timeunit=None, subcalls=True, builtins=True) + + Builds a profiler object using the specified timer function. + The default timer is a fast built-in one based on real time. +- For custom timer functions returning integers, time_unit can ++ For custom timer functions returning integers, timeunit can + be a float specifying a scale (i.e. how long each integer unit + is, in seconds). + """ +diff --git a/Lib/cgitb.py b/Lib/cgitb.py +index 8acc4b75fe..3689f8a4ba 100644 +--- a/Lib/cgitb.py ++++ b/Lib/cgitb.py +@@ -125,7 +125,7 @@ function calls leading up to the error, in the order they occurred.

''' + args, varargs, varkw, locals = inspect.getargvalues(frame) + call = '' + if func != '?': +- call = 'in ' + strong(func) + \ ++ call = 'in ' + strong(pydoc.html.escape(func)) + \ + inspect.formatargvalues(args, varargs, varkw, locals, + formatvalue=lambda value: '=' + pydoc.html.repr(value)) + +@@ -285,7 +285,7 @@ class Hook: + + if self.display: + if plain: +- doc = doc.replace('&', '&').replace('<', '<') ++ doc = pydoc.html.escape(doc) + self.file.write('
' + doc + '
\n') + else: + self.file.write(doc + '\n') +diff --git a/Lib/ctypes/test/test_as_parameter.py b/Lib/ctypes/test/test_as_parameter.py +index f2fe10a955..de730e95bb 100644 +--- a/Lib/ctypes/test/test_as_parameter.py ++++ b/Lib/ctypes/test/test_as_parameter.py +@@ -24,7 +24,7 @@ class BasicWrapTestCase(unittest.TestCase): + f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double] + result = f(self.wrap(1), self.wrap(u"x"), self.wrap(3), self.wrap(4), self.wrap(5.0), self.wrap(6.0)) + self.assertEqual(result, 139) +- self.assertTrue(type(result), int) ++ self.assertIs(type(result), int) + + def test_pointers(self): + f = dll._testfunc_p_p +diff --git a/Lib/ctypes/test/test_callbacks.py b/Lib/ctypes/test/test_callbacks.py +index bf894d481c..db3d9e7b19 100644 +--- a/Lib/ctypes/test/test_callbacks.py ++++ b/Lib/ctypes/test/test_callbacks.py +@@ -250,6 +250,7 @@ class SampleCallbacksTestCase(unittest.TestCase): + def test_callback_large_struct(self): + class Check: pass + ++ # This should mirror the structure in Modules/_ctypes/_ctypes_test.c + class X(Structure): + _fields_ = [ + ('first', c_ulong), +@@ -261,6 +262,11 @@ class SampleCallbacksTestCase(unittest.TestCase): + check.first = s.first + check.second = s.second + check.third = s.third ++ # See issue #29565. ++ # The structure should be passed by value, so ++ # any changes to it should not be reflected in ++ # the value passed ++ s.first = s.second = s.third = 0x0badf00d + + check = Check() + s = X() +@@ -281,6 +287,11 @@ class SampleCallbacksTestCase(unittest.TestCase): + self.assertEqual(check.first, 0xdeadbeef) + self.assertEqual(check.second, 0xcafebabe) + self.assertEqual(check.third, 0x0bad1dea) ++ # See issue #29565. ++ # Ensure that the original struct is unchanged. ++ self.assertEqual(s.first, check.first) ++ self.assertEqual(s.second, check.second) ++ self.assertEqual(s.third, check.third) + + ################################################################ + +diff --git a/Lib/ctypes/test/test_structures.py b/Lib/ctypes/test/test_structures.py +index 5650189f8a..9a863c94da 100644 +--- a/Lib/ctypes/test/test_structures.py ++++ b/Lib/ctypes/test/test_structures.py +@@ -3,6 +3,7 @@ from ctypes import * + from ctypes.test import need_symbol + from struct import calcsize + import _testcapi ++import _ctypes_test + + class SubclassesTest(unittest.TestCase): + def test_subclass(self): +@@ -401,6 +402,28 @@ class StructureTestCase(unittest.TestCase): + (1, 0, 0, 0, 0, 0)) + self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7)) + ++ def test_pass_by_value(self): ++ # This should mirror the structure in Modules/_ctypes/_ctypes_test.c ++ class X(Structure): ++ _fields_ = [ ++ ('first', c_ulong), ++ ('second', c_ulong), ++ ('third', c_ulong), ++ ] ++ ++ s = X() ++ s.first = 0xdeadbeef ++ s.second = 0xcafebabe ++ s.third = 0x0bad1dea ++ dll = CDLL(_ctypes_test.__file__) ++ func = dll._testfunc_large_struct_update_value ++ func.argtypes = (X,) ++ func.restype = None ++ func(s) ++ self.assertEqual(s.first, 0xdeadbeef) ++ self.assertEqual(s.second, 0xcafebabe) ++ self.assertEqual(s.third, 0x0bad1dea) ++ + class PointerMemberTestCase(unittest.TestCase): + + def test(self): +diff --git a/Lib/ctypes/test/test_win32.py b/Lib/ctypes/test/test_win32.py +index d22e139a3f..13a986359f 100644 +--- a/Lib/ctypes/test/test_win32.py ++++ b/Lib/ctypes/test/test_win32.py +@@ -52,6 +52,24 @@ class FunctionCallTestCase(unittest.TestCase): + # This is a special case on win32 x64 + windll.user32.GetDesktopWindow() + ++@unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') ++class ReturnStructSizesTestCase(unittest.TestCase): ++ def test_sizes(self): ++ dll = CDLL(_ctypes_test.__file__) ++ for i in range(1, 11): ++ fields = [ ("f%d" % f, c_char) for f in range(1, i + 1)] ++ class S(Structure): ++ _fields_ = fields ++ f = getattr(dll, "TestSize%d" % i) ++ f.restype = S ++ res = f() ++ for i, f in enumerate(fields): ++ value = getattr(res, f[0]) ++ expected = chr(ord('a') + i) ++ self.assertEquals(value, expected) ++ ++ ++ + @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') + class TestWintypes(unittest.TestCase): + def test_HWND(self): +diff --git a/Lib/curses/has_key.py b/Lib/curses/has_key.py +index 1dd5a3bd4a..60b7be9942 100644 +--- a/Lib/curses/has_key.py ++++ b/Lib/curses/has_key.py +@@ -182,7 +182,7 @@ if __name__ == '__main__': + L = [] + _curses.initscr() + for key in _capability_names.keys(): +- system = key in _curses ++ system = _curses.has_key(key) + python = has_key(key) + if system != python: + L.append( 'Mismatch for key %s, system=%i, Python=%i' +diff --git a/Lib/distutils/spawn.py b/Lib/distutils/spawn.py +index 321344a3a5..737b293f8d 100644 +--- a/Lib/distutils/spawn.py ++++ b/Lib/distutils/spawn.py +@@ -208,7 +208,8 @@ def find_executable(executable, path=None): + os.environ['PATH']. Returns the complete filename or None if not found. + """ + if path is None: +- path = os.environ['PATH'] ++ path = os.environ.get('PATH', os.defpath) ++ + paths = path.split(os.pathsep) + base, ext = os.path.splitext(executable) + +diff --git a/Lib/distutils/tests/test_check.py b/Lib/distutils/tests/test_check.py +index 81058b1911..e94647ffa4 100644 +--- a/Lib/distutils/tests/test_check.py ++++ b/Lib/distutils/tests/test_check.py +@@ -8,6 +8,12 @@ from distutils.command.check import check, HAS_DOCUTILS + from distutils.tests import support + from distutils.errors import DistutilsSetupError + ++try: ++ import pygments ++except ImportError: ++ pygments = None ++ ++ + class CheckTestCase(support.LoggingSilencer, + support.TempdirManager, + unittest.TestCase): +@@ -120,9 +126,15 @@ class CheckTestCase(support.LoggingSilencer, + pkg_info, dist = self.create_dist(long_description=rest_with_code) + cmd = check(dist) + cmd.check_restructuredtext() +- self.assertEqual(cmd._warnings, 0) + msgs = cmd._check_rst_data(rest_with_code) +- self.assertEqual(len(msgs), 0) ++ if pygments is not None: ++ self.assertEqual(len(msgs), 0) ++ else: ++ self.assertEqual(len(msgs), 1) ++ self.assertEqual( ++ str(msgs[0][1]), ++ 'Cannot analyze code. Pygments package not found.' ++ ) + + def test_check_all(self): + +diff --git a/Lib/distutils/tests/test_spawn.py b/Lib/distutils/tests/test_spawn.py +index defa54d87f..061a72f1a5 100644 +--- a/Lib/distutils/tests/test_spawn.py ++++ b/Lib/distutils/tests/test_spawn.py +@@ -1,8 +1,11 @@ + """Tests for distutils.spawn.""" +-import unittest + import os ++import stat ++import sys + import time +-from test.test_support import captured_stdout, run_unittest ++import unittest ++from test.support import captured_stdout, run_unittest ++from test import support as test_support + + from distutils.spawn import _nt_quote_args + from distutils.spawn import spawn, find_executable +@@ -53,6 +56,48 @@ class SpawnTestCase(support.TempdirManager, + os.chmod(exe, 0777) + spawn([exe]) # should work without any error + ++ def test_find_executable(self): ++ with test_support.temp_dir() as tmp_dir: ++ # use TESTFN to get a pseudo-unique filename ++ program_noeext = test_support.TESTFN ++ # Give the temporary program an ".exe" suffix for all. ++ # It's needed on Windows and not harmful on other platforms. ++ program = program_noeext + ".exe" ++ ++ filename = os.path.join(tmp_dir, program) ++ with open(filename, "wb"): ++ pass ++ os.chmod(filename, stat.S_IXUSR) ++ ++ # test path parameter ++ rv = find_executable(program, path=tmp_dir) ++ self.assertEqual(rv, filename) ++ ++ if sys.platform == 'win32': ++ # test without ".exe" extension ++ rv = find_executable(program_noeext, path=tmp_dir) ++ self.assertEqual(rv, filename) ++ ++ # test find in the current directory ++ with test_support.change_cwd(tmp_dir): ++ rv = find_executable(program) ++ self.assertEqual(rv, program) ++ ++ # test non-existent program ++ dont_exist_program = "dontexist_" + program ++ rv = find_executable(dont_exist_program , path=tmp_dir) ++ self.assertIsNone(rv) ++ ++ # test os.defpath: missing PATH environment variable ++ with test_support.EnvironmentVarGuard() as env: ++ from distutils import spawn ++ with test_support.swap_attr(spawn.os, 'defpath', tmp_dir): ++ env.pop('PATH') ++ ++ rv = find_executable(program) ++ self.assertEqual(rv, filename) ++ ++ + def test_suite(): + return unittest.makeSuite(SpawnTestCase) + +diff --git a/Lib/ensurepip/__init__.py b/Lib/ensurepip/__init__.py +index 89ed1efdaf..3c679e5968 100644 +--- a/Lib/ensurepip/__init__.py ++++ b/Lib/ensurepip/__init__.py +@@ -14,7 +14,7 @@ __all__ = ["version", "bootstrap"] + + _SETUPTOOLS_VERSION = "39.0.1" + +-_PIP_VERSION = "9.0.3" ++_PIP_VERSION = "10.0.1" + + _PROJECTS = [ + ("setuptools", _SETUPTOOLS_VERSION), +@@ -28,8 +28,8 @@ def _run_pip(args, additional_paths=None): + sys.path = additional_paths + sys.path + + # Install the bundled software +- import pip +- return pip.main(args) ++ import pip._internal ++ return pip._internal.main(args) + + + def version(): +@@ -190,8 +190,8 @@ def _main(argv=None): + "--altinstall", + action="store_true", + default=False, +- help=("Make an alternate install, installing only the X.Y versioned" +- "scripts (Default: pipX, pipX.Y, easy_install-X.Y)"), ++ help=("Make an alternate install, installing only the X.Y versioned " ++ "scripts (Default: pipX, pipX.Y, easy_install-X.Y)."), + ) + parser.add_argument( + "--default-pip", +diff --git a/Lib/gzip.py b/Lib/gzip.py +index 07c6db493b..76ace394f4 100644 +--- a/Lib/gzip.py ++++ b/Lib/gzip.py +@@ -95,9 +95,8 @@ class GzipFile(io.BufferedIOBase): + if filename is None: + # Issue #13781: os.fdopen() creates a fileobj with a bogus name + # attribute. Avoid saving this in the gzip header's filename field. +- if hasattr(fileobj, 'name') and fileobj.name != '': +- filename = fileobj.name +- else: ++ filename = getattr(fileobj, 'name', '') ++ if not isinstance(filename, basestring) or filename == '': + filename = '' + if mode is None: + if hasattr(fileobj, 'mode'): mode = fileobj.mode +diff --git a/Lib/httplib.py b/Lib/httplib.py +index f3bb22c2b6..60a8fb4e35 100644 +--- a/Lib/httplib.py ++++ b/Lib/httplib.py +@@ -399,7 +399,7 @@ class HTTPResponse: + if not line: + # Presumably, the server closed the connection before + # sending a valid response. +- raise BadStatusLine(line) ++ raise BadStatusLine("No status line received - the server has closed the connection") + try: + [version, status, reason] = line.split(None, 2) + except ValueError: +diff --git a/Lib/idlelib/CallTipWindow.py b/Lib/idlelib/CallTipWindow.py +index e63164b5a0..2a453d06f5 100644 +--- a/Lib/idlelib/CallTipWindow.py ++++ b/Lib/idlelib/CallTipWindow.py +@@ -72,6 +72,7 @@ class CallTip: + background="#ffffe0", relief=SOLID, borderwidth=1, + font = self.widget['font']) + self.label.pack() ++ tw.update_idletasks() + tw.lift() # work around bug in Tk 8.5.18+ (issue #24570) + + self.checkhideid = self.widget.bind(CHECKHIDE_VIRTUAL_EVENT_NAME, +diff --git a/Lib/idlelib/NEWS.txt b/Lib/idlelib/NEWS.txt +index 35e2a7ecce..257e28833e 100644 +--- a/Lib/idlelib/NEWS.txt ++++ b/Lib/idlelib/NEWS.txt +@@ -1,6 +1,19 @@ ++Since 2.7.13, only severe bugs are fixed on the 2.7 branch. ++ ++What's New in IDLE 2.7.16? ++========================== ++*Release date: 2019-01-01?* ++ ++bpo-34275: Make calltips always visible on Mac. ++Patch by Kevin Walzer. ++ ++bpo-34120: Fix freezing after closing some dialogs on Mac. ++This is one of multiple regressions from using newer tcl/tk. ++ ++ + What's New in IDLE 2.7.13? + ========================== +-*Release date: 2017-01-01?* ++*Release date: 2016-12-17* + + - Issue #27854: Make Help => IDLE Help work again on Windows. + Include idlelib/help.html in 2.7 Windows installer. +@@ -35,7 +48,7 @@ What's New in IDLE 2.7.13? + + What's New in IDLE 2.7.12? + ========================== +-*Release date: 2015-06-25* ++*Release date: 2016-06-25* + + - Issue #5124: Paste with text selected now replaces the selection on X11. + This matches how paste works on Windows, Mac, most modern Linux apps, +diff --git a/Lib/idlelib/PyShell.py b/Lib/idlelib/PyShell.py +index fdd7cb1c4e..337530ab88 100755 +--- a/Lib/idlelib/PyShell.py ++++ b/Lib/idlelib/PyShell.py +@@ -1040,7 +1040,7 @@ class PyShell(OutputWindow): + return self.shell_title + + COPYRIGHT = \ +- 'Type "copyright", "credits" or "license()" for more information.' ++ 'Type "help", "copyright", "credits" or "license()" for more information.' + + def begin(self): + self.resetoutput() +diff --git a/Lib/idlelib/aboutDialog.py b/Lib/idlelib/aboutDialog.py +index c9adc08bb2..87d6c3cb9c 100644 +--- a/Lib/idlelib/aboutDialog.py ++++ b/Lib/idlelib/aboutDialog.py +@@ -141,6 +141,7 @@ class AboutDialog(Toplevel): + textView.view_file(self, title, fn, encoding) + + def Ok(self, event=None): ++ self.grab_release() + self.destroy() + + if __name__ == '__main__': +diff --git a/Lib/idlelib/configDialog.py b/Lib/idlelib/configDialog.py +index d53f5ff200..3c29af1376 100644 +--- a/Lib/idlelib/configDialog.py ++++ b/Lib/idlelib/configDialog.py +@@ -1197,10 +1197,12 @@ class ConfigDialog(Toplevel): + instance.reset_help_menu_entries() + + def Cancel(self): ++ self.grab_release() + self.destroy() + + def Ok(self): + self.Apply() ++ self.grab_release() + self.destroy() + + def Apply(self): +diff --git a/Lib/idlelib/configHelpSourceEdit.py b/Lib/idlelib/configHelpSourceEdit.py +index 5816449caf..62b010a0ca 100644 +--- a/Lib/idlelib/configHelpSourceEdit.py ++++ b/Lib/idlelib/configHelpSourceEdit.py +@@ -155,10 +155,12 @@ class GetHelpSourceDialog(Toplevel): + # Mac Safari insists on using the URI form for local files + self.result = list(self.result) + self.result[1] = "file://" + path ++ self.grab_release() + self.destroy() + + def Cancel(self, event=None): + self.result = None ++ self.grab_release() + self.destroy() + + if __name__ == '__main__': +diff --git a/Lib/idlelib/configSectionNameDialog.py b/Lib/idlelib/configSectionNameDialog.py +index c09dca896b..f28dc1a283 100644 +--- a/Lib/idlelib/configSectionNameDialog.py ++++ b/Lib/idlelib/configSectionNameDialog.py +@@ -80,10 +80,13 @@ class GetCfgSectionNameDialog(Toplevel): + name = self.name_ok() + if name: + self.result = name ++ self.grab_release() + self.destroy() + def Cancel(self, event=None): + self.result = '' ++ self.grab_release() + self.destroy() ++ + if __name__ == '__main__': + import unittest + unittest.main('idlelib.idle_test.test_config_name', verbosity=2, exit=False) +diff --git a/Lib/idlelib/idle_test/test_config_name.py b/Lib/idlelib/idle_test/test_config_name.py +index 4403f87fd3..2a4df6a744 100644 +--- a/Lib/idlelib/idle_test/test_config_name.py ++++ b/Lib/idlelib/idle_test/test_config_name.py +@@ -15,6 +15,8 @@ class Dummy_name_dialog(object): + name = Var() + result = None + destroyed = False ++ def grab_release(self): ++ pass + def destroy(self): + self.destroyed = True + +diff --git a/Lib/idlelib/keybindingDialog.py b/Lib/idlelib/keybindingDialog.py +index 4d32ca9476..755f1af47e 100644 +--- a/Lib/idlelib/keybindingDialog.py ++++ b/Lib/idlelib/keybindingDialog.py +@@ -217,10 +217,12 @@ class GetKeysDialog(Toplevel): + def OK(self, event=None): + if self.advanced or self.KeysOK(): # doesn't check advanced string yet + self.result=self.keyString.get() ++ self.grab_release() + self.destroy() + + def Cancel(self, event=None): + self.result='' ++ self.grab_release() + self.destroy() + + def KeysOK(self): +diff --git a/Lib/idlelib/textView.py b/Lib/idlelib/textView.py +index b8c4ac1821..ec837f810c 100644 +--- a/Lib/idlelib/textView.py ++++ b/Lib/idlelib/textView.py +@@ -39,7 +39,8 @@ class TextViewer(Toplevel): + self.textView.insert(0.0, text) + self.textView.config(state=DISABLED) + +- if modal: ++ self.is_modal = modal ++ if self.is_modal: + self.transient(parent) + self.grab_set() + self.wait_window() +@@ -62,6 +63,8 @@ class TextViewer(Toplevel): + frameText.pack(side=TOP,expand=TRUE,fill=BOTH) + + def Ok(self, event=None): ++ if self.is_modal: ++ self.grab_release() + self.destroy() + + +diff --git a/Lib/imaplib.py b/Lib/imaplib.py +index 220d6e1bc0..2e5511e024 100644 +--- a/Lib/imaplib.py ++++ b/Lib/imaplib.py +@@ -70,6 +70,7 @@ Commands = { + 'LOGIN': ('NONAUTH',), + 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'), + 'LSUB': ('AUTH', 'SELECTED'), ++ 'MOVE': ('SELECTED',), + 'NAMESPACE': ('AUTH', 'SELECTED'), + 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'), + 'PARTIAL': ('SELECTED',), # NB: obsolete +diff --git a/Lib/inspect.py b/Lib/inspect.py +index 0a6cfd7951..cbced17373 100644 +--- a/Lib/inspect.py ++++ b/Lib/inspect.py +@@ -688,8 +688,15 @@ def getsourcelines(object): + raised if the source code cannot be retrieved.""" + lines, lnum = findsource(object) + +- if ismodule(object): return lines, 0 +- else: return getblock(lines[lnum:]), lnum + 1 ++ if istraceback(object): ++ object = object.tb_frame ++ ++ # for module or frame that corresponds to module, return all source lines ++ if (ismodule(object) or ++ (isframe(object) and object.f_code.co_name == "")): ++ return lines, 0 ++ else: ++ return getblock(lines[lnum:]), lnum + 1 + + def getsource(object): + """Return the text of the source code for an object. +diff --git a/Lib/lib-tk/Tkinter.py b/Lib/lib-tk/Tkinter.py +index 6198c4c949..2f3a3f12a5 100644 +--- a/Lib/lib-tk/Tkinter.py ++++ b/Lib/lib-tk/Tkinter.py +@@ -71,7 +71,7 @@ def _stringify(value): + if isinstance(value, (list, tuple)): + if len(value) == 1: + value = _stringify(value[0]) +- if value[0] == '{': ++ if _magic_re.search(value): + value = '{%s}' % value + else: + value = '{%s}' % _join(value) +@@ -85,7 +85,10 @@ def _stringify(value): + elif _magic_re.search(value): + # add '\' before special characters and spaces + value = _magic_re.sub(r'\\\1', value) ++ value = value.replace('\n', r'\n') + value = _space_re.sub(r'\\\1', value) ++ if value[0] == '"': ++ value = '\\' + value + elif value[0] == '"' or _space_re.search(value): + value = '{%s}' % value + return value +@@ -586,6 +589,7 @@ class Misc: + if not func: + # I'd rather use time.sleep(ms*0.001) + self.tk.call('after', ms) ++ return None + else: + def callit(): + try: +@@ -609,11 +613,13 @@ class Misc: + """Cancel scheduling of function identified with ID. + + Identifier returned by after or after_idle must be +- given as first parameter.""" ++ given as first parameter. ++ """ ++ if not id: ++ raise ValueError('id must be a valid identifier returned from ' ++ 'after or after_idle') + try: + data = self.tk.call('after', 'info', id) +- # In Tk 8.3, splitlist returns: (script, type) +- # In Tk 8.4, splitlist may return (script, type) or (script,) + script = self.tk.splitlist(data)[0] + self.deletecommand(script) + except TclError: +@@ -3362,7 +3368,7 @@ class Image: + self.tk.call('image', 'width', self.name)) + + class PhotoImage(Image): +- """Widget which can display colored images in GIF, PPM/PGM format.""" ++ """Widget which can display images in PGM, PPM, GIF, PNG format.""" + def __init__(self, name=None, cnf={}, master=None, **kw): + """Create an image with NAME. + +@@ -3426,7 +3432,7 @@ class PhotoImage(Image): + self.tk.call(args) + + class BitmapImage(Image): +- """Widget which can display a bitmap.""" ++ """Widget which can display images in XBM format.""" + def __init__(self, name=None, cnf={}, master=None, **kw): + """Create a bitmap with NAME. + +diff --git a/Lib/lib-tk/test/test_tkinter/test_misc.py b/Lib/lib-tk/test/test_tkinter/test_misc.py +new file mode 100644 +index 0000000000..796269ede4 +--- /dev/null ++++ b/Lib/lib-tk/test/test_tkinter/test_misc.py +@@ -0,0 +1,122 @@ ++import unittest ++import Tkinter as tkinter ++from test.test_support import requires, run_unittest ++from test_ttk.support import AbstractTkTest ++ ++requires('gui') ++ ++class MiscTest(AbstractTkTest, unittest.TestCase): ++ ++ def test_after(self): ++ root = self.root ++ cbcount = {'count': 0} ++ ++ def callback(start=0, step=1): ++ cbcount['count'] = start + step ++ ++ # Without function, sleeps for ms. ++ self.assertIsNone(root.after(1)) ++ ++ # Set up with callback with no args. ++ cbcount['count'] = 0 ++ timer1 = root.after(0, callback) ++ self.assertIn(timer1, root.tk.call('after', 'info')) ++ (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1)) ++ root.update() # Process all pending events. ++ self.assertEqual(cbcount['count'], 1) ++ with self.assertRaises(tkinter.TclError): ++ root.tk.call(script) ++ ++ # Set up with callback with args. ++ cbcount['count'] = 0 ++ timer1 = root.after(0, callback, 42, 11) ++ root.update() # Process all pending events. ++ self.assertEqual(cbcount['count'], 53) ++ ++ # Cancel before called. ++ timer1 = root.after(1000, callback) ++ self.assertIn(timer1, root.tk.call('after', 'info')) ++ (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1)) ++ root.after_cancel(timer1) # Cancel this event. ++ self.assertEqual(cbcount['count'], 53) ++ with self.assertRaises(tkinter.TclError): ++ root.tk.call(script) ++ ++ def test_after_idle(self): ++ root = self.root ++ cbcount = {'count': 0} ++ ++ def callback(start=0, step=1): ++ cbcount['count'] = start + step ++ ++ # Set up with callback with no args. ++ cbcount['count'] = 0 ++ idle1 = root.after_idle(callback) ++ self.assertIn(idle1, root.tk.call('after', 'info')) ++ (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1)) ++ root.update_idletasks() # Process all pending events. ++ self.assertEqual(cbcount['count'], 1) ++ with self.assertRaises(tkinter.TclError): ++ root.tk.call(script) ++ ++ # Set up with callback with args. ++ cbcount['count'] = 0 ++ idle1 = root.after_idle(callback, 42, 11) ++ root.update_idletasks() # Process all pending events. ++ self.assertEqual(cbcount['count'], 53) ++ ++ # Cancel before called. ++ idle1 = root.after_idle(callback) ++ self.assertIn(idle1, root.tk.call('after', 'info')) ++ (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1)) ++ root.after_cancel(idle1) # Cancel this event. ++ self.assertEqual(cbcount['count'], 53) ++ with self.assertRaises(tkinter.TclError): ++ root.tk.call(script) ++ ++ def test_after_cancel(self): ++ root = self.root ++ cbcount = {'count': 0} ++ ++ def callback(): ++ cbcount['count'] += 1 ++ ++ timer1 = root.after(5000, callback) ++ idle1 = root.after_idle(callback) ++ ++ # No value for id raises a ValueError. ++ with self.assertRaises(ValueError): ++ root.after_cancel(None) ++ ++ # Cancel timer event. ++ cbcount['count'] = 0 ++ (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1)) ++ root.tk.call(script) ++ self.assertEqual(cbcount['count'], 1) ++ root.after_cancel(timer1) ++ with self.assertRaises(tkinter.TclError): ++ root.tk.call(script) ++ self.assertEqual(cbcount['count'], 1) ++ with self.assertRaises(tkinter.TclError): ++ root.tk.call('after', 'info', timer1) ++ ++ # Cancel same event - nothing happens. ++ root.after_cancel(timer1) ++ ++ # Cancel idle event. ++ cbcount['count'] = 0 ++ (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1)) ++ root.tk.call(script) ++ self.assertEqual(cbcount['count'], 1) ++ root.after_cancel(idle1) ++ with self.assertRaises(tkinter.TclError): ++ root.tk.call(script) ++ self.assertEqual(cbcount['count'], 1) ++ with self.assertRaises(tkinter.TclError): ++ root.tk.call('after', 'info', idle1) ++ ++ ++tests_gui = (MiscTest, ) ++ ++if __name__ == "__main__": ++ run_unittest(*tests_gui) +diff --git a/Lib/lib-tk/test/test_tkinter/test_widgets.py b/Lib/lib-tk/test/test_tkinter/test_widgets.py +index 1f60204d4a..db2cd9db24 100644 +--- a/Lib/lib-tk/test/test_tkinter/test_widgets.py ++++ b/Lib/lib-tk/test/test_tkinter/test_widgets.py +@@ -700,7 +700,7 @@ class ListboxTest(AbstractWidgetTest, unittest.TestCase): + 'disabledforeground', 'exportselection', + 'font', 'foreground', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', +- 'listvariable', 'relief', ++ 'justify', 'listvariable', 'relief', + 'selectbackground', 'selectborderwidth', 'selectforeground', + 'selectmode', 'setgrid', 'state', + 'takefocus', 'width', 'xscrollcommand', 'yscrollcommand', +@@ -714,6 +714,8 @@ class ListboxTest(AbstractWidgetTest, unittest.TestCase): + self.checkEnumParam(widget, 'activestyle', + 'dotbox', 'none', 'underline') + ++ test_justify = requires_tcl(8, 6, 5)(StandardOptionsTests.test_justify.im_func) ++ + def test_listvariable(self): + widget = self.create() + var = tkinter.DoubleVar(self.root) +@@ -947,7 +949,9 @@ class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'background', 'borderwidth', 'cursor', + 'handlepad', 'handlesize', 'height', +- 'opaqueresize', 'orient', 'relief', ++ 'opaqueresize', 'orient', ++ 'proxybackground', 'proxyborderwidth', 'proxyrelief', ++ 'relief', + 'sashcursor', 'sashpad', 'sashrelief', 'sashwidth', + 'showhandle', 'width', + ) +@@ -974,6 +978,23 @@ class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): + widget = self.create() + self.checkBooleanParam(widget, 'opaqueresize') + ++ @requires_tcl(8, 6, 5) ++ def test_proxybackground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'proxybackground') ++ ++ @requires_tcl(8, 6, 5) ++ def test_proxyborderwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'proxyborderwidth', ++ 0, 1.3, 2.9, 6, -2, '10p', ++ conv=noconv) ++ ++ @requires_tcl(8, 6, 5) ++ def test_proxyrelief(self): ++ widget = self.create() ++ self.checkReliefParam(widget, 'proxyrelief') ++ + def test_sashcursor(self): + widget = self.create() + self.checkCursorParam(widget, 'sashcursor') +diff --git a/Lib/lib-tk/test/test_ttk/support.py b/Lib/lib-tk/test/test_ttk/support.py +index c4d842aac1..cb8eae257a 100644 +--- a/Lib/lib-tk/test/test_ttk/support.py ++++ b/Lib/lib-tk/test/test_ttk/support.py +@@ -1,3 +1,4 @@ ++import functools + import re + import unittest + import Tkinter as tkinter +@@ -54,9 +55,20 @@ import _tkinter + tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.'))) + + def requires_tcl(*version): +- return unittest.skipUnless(tcl_version >= version, ++ if len(version) <= 2: ++ return unittest.skipUnless(tcl_version >= version, + 'requires Tcl version >= ' + '.'.join(map(str, version))) + ++ def deco(test): ++ @functools.wraps(test) ++ def newtest(self): ++ if get_tk_patchlevel() < (8, 6, 5): ++ self.skipTest('requires Tcl version >= ' + ++ '.'.join(map(str, get_tk_patchlevel()))) ++ test(self) ++ return newtest ++ return deco ++ + _tk_patchlevel = None + def get_tk_patchlevel(): + global _tk_patchlevel +diff --git a/Lib/locale.py b/Lib/locale.py +index 62aad5ae7b..51909f81e7 100644 +--- a/Lib/locale.py ++++ b/Lib/locale.py +@@ -798,6 +798,17 @@ locale_encoding_alias = { + # + # SS 2014-10-01: + # Updated alias mapping with glibc 2.19 supported locales. ++# ++# SS 2018-05-05: ++# Updated alias mapping with glibc 2.27 supported locales. ++# ++# These are the differences compared to the old mapping (Python 2.7.15 ++# and older): ++# ++# updated 'ca_es@valencia' -> 'ca_ES.ISO8859-15@valencia' to 'ca_ES.UTF-8@valencia' ++# updated 'english.iso88591' -> 'en_EN.ISO8859-1' to 'en_US.ISO8859-1' ++# updated 'kk_kz' -> 'kk_KZ.RK1048' to 'kk_KZ.ptcp154' ++# updated 'russian' -> 'ru_RU.ISO8859-5' to 'ru_RU.KOI8-R' + + locale_alias = { + 'a3': 'az_AZ.KOI8-C', +@@ -810,11 +821,14 @@ locale_alias = { + 'af': 'af_ZA.ISO8859-1', + 'af_za': 'af_ZA.ISO8859-1', + 'af_za.iso88591': 'af_ZA.ISO8859-1', ++ 'agr_pe': 'agr_PE.UTF-8', ++ 'ak_gh': 'ak_GH.UTF-8', + 'am': 'am_ET.UTF-8', + 'am_et': 'am_ET.UTF-8', + 'american': 'en_US.ISO8859-1', + 'american.iso88591': 'en_US.ISO8859-1', + 'an_es': 'an_ES.ISO8859-15', ++ 'anp_in': 'anp_IN.UTF-8', + 'ar': 'ar_AA.ISO8859-6', + 'ar_aa': 'ar_AA.ISO8859-6', + 'ar_aa.iso88596': 'ar_AA.ISO8859-6', +@@ -847,6 +861,7 @@ locale_alias = { + 'ar_sa.iso88596': 'ar_SA.ISO8859-6', + 'ar_sd': 'ar_SD.ISO8859-6', + 'ar_sd.iso88596': 'ar_SD.ISO8859-6', ++ 'ar_ss': 'ar_SS.UTF-8', + 'ar_sy': 'ar_SY.ISO8859-6', + 'ar_sy.iso88596': 'ar_SY.ISO8859-6', + 'ar_tn': 'ar_TN.ISO8859-6', +@@ -862,6 +877,7 @@ locale_alias = { + 'az': 'az_AZ.ISO8859-9E', + 'az_az': 'az_AZ.ISO8859-9E', + 'az_az.iso88599e': 'az_AZ.ISO8859-9E', ++ 'az_ir': 'az_IR.UTF-8', + 'be': 'be_BY.CP1251', + 'be@latin': 'be_BY.UTF-8@latin', + 'be_bg.utf8': 'bg_BG.UTF-8', +@@ -879,7 +895,10 @@ locale_alias = { + 'bg_bg.iso88595': 'bg_BG.ISO8859-5', + 'bg_bg.koi8r': 'bg_BG.KOI8-R', + 'bg_bg.microsoftcp1251': 'bg_BG.CP1251', ++ 'bhb_in.utf8': 'bhb_IN.UTF-8', + 'bho_in': 'bho_IN.UTF-8', ++ 'bho_np': 'bho_NP.UTF-8', ++ 'bi_vu': 'bi_VU.UTF-8', + 'bn_bd': 'bn_BD.UTF-8', + 'bn_in': 'bn_IN.UTF-8', + 'bo_cn': 'bo_CN.UTF-8', +@@ -921,8 +940,8 @@ locale_alias = { + 'ca_es.iso885915': 'ca_ES.ISO8859-15', + 'ca_es.iso885915@euro': 'ca_ES.ISO8859-15', + 'ca_es.utf8@euro': 'ca_ES.UTF-8', +- 'ca_es@valencia': 'ca_ES.ISO8859-15@valencia', + 'ca_es@euro': 'ca_ES.ISO8859-15', ++ 'ca_es@valencia': 'ca_ES.UTF-8@valencia', + 'ca_fr': 'ca_FR.ISO8859-1', + 'ca_fr.iso88591': 'ca_FR.ISO8859-1', + 'ca_fr.iso885915': 'ca_FR.ISO8859-15', +@@ -936,10 +955,14 @@ locale_alias = { + 'ca_it.utf8@euro': 'ca_IT.UTF-8', + 'ca_it@euro': 'ca_IT.ISO8859-15', + 'catalan': 'ca_ES.ISO8859-1', ++ 'ce_ru': 'ce_RU.UTF-8', + 'cextend': 'en_US.ISO8859-1', + 'cextend.en': 'en_US.ISO8859-1', + 'chinese-s': 'zh_CN.eucCN', + 'chinese-t': 'zh_TW.eucTW', ++ 'chr_us': 'chr_US.UTF-8', ++ 'ckb_iq': 'ckb_IQ.UTF-8', ++ 'cmn_tw': 'cmn_TW.UTF-8', + 'crh_ua': 'crh_UA.UTF-8', + 'croatian': 'hr_HR.ISO8859-2', + 'cs': 'cs_CZ.ISO8859-2', +@@ -996,6 +1019,7 @@ locale_alias = { + 'de_de.iso885915@euro': 'de_DE.ISO8859-15', + 'de_de.utf8@euro': 'de_DE.UTF-8', + 'de_de@euro': 'de_DE.ISO8859-15', ++ 'de_it': 'de_IT.ISO8859-1', + 'de_li.utf8': 'de_LI.UTF-8', + 'de_lu': 'de_LU.ISO8859-1', + 'de_lu.iso88591': 'de_LU.ISO8859-1', +@@ -1030,6 +1054,8 @@ locale_alias = { + 'en_ca': 'en_CA.ISO8859-1', + 'en_ca.iso88591': 'en_CA.ISO8859-1', + 'en_dk': 'en_DK.ISO8859-1', ++ 'en_dk.iso88591': 'en_DK.ISO8859-1', ++ 'en_dk.iso885915': 'en_DK.ISO8859-15', + 'en_dl.utf8': 'en_DL.UTF-8', + 'en_gb': 'en_GB.ISO8859-1', + 'en_gb.88591': 'en_GB.ISO8859-1', +@@ -1044,12 +1070,14 @@ locale_alias = { + 'en_ie.iso885915@euro': 'en_IE.ISO8859-15', + 'en_ie.utf8@euro': 'en_IE.UTF-8', + 'en_ie@euro': 'en_IE.ISO8859-15', ++ 'en_il': 'en_IL.UTF-8', + 'en_in': 'en_IN.ISO8859-1', + 'en_ng': 'en_NG.UTF-8', + 'en_nz': 'en_NZ.ISO8859-1', + 'en_nz.iso88591': 'en_NZ.ISO8859-1', + 'en_ph': 'en_PH.ISO8859-1', + 'en_ph.iso88591': 'en_PH.ISO8859-1', ++ 'en_sc.utf8': 'en_SC.UTF-8', + 'en_sg': 'en_SG.ISO8859-1', + 'en_sg.iso88591': 'en_SG.ISO8859-1', + 'en_uk': 'en_GB.ISO8859-1', +@@ -1073,7 +1101,7 @@ locale_alias = { + 'eng_gb': 'en_GB.ISO8859-1', + 'eng_gb.8859': 'en_GB.ISO8859-1', + 'english': 'en_EN.ISO8859-1', +- 'english.iso88591': 'en_EN.ISO8859-1', ++ 'english.iso88591': 'en_US.ISO8859-1', + 'english_uk': 'en_GB.ISO8859-1', + 'english_uk.8859': 'en_GB.ISO8859-1', + 'english_united-states': 'en_US.ISO8859-1', +@@ -1268,6 +1296,7 @@ locale_alias = { + 'gv_gb.iso885915': 'gv_GB.ISO8859-15', + 'gv_gb@euro': 'gv_GB.ISO8859-15', + 'ha_ng': 'ha_NG.UTF-8', ++ 'hak_tw': 'hak_TW.UTF-8', + 'he': 'he_IL.ISO8859-8', + 'he_il': 'he_IL.ISO8859-8', + 'he_il.cp1255': 'he_IL.CP1255', +@@ -1278,6 +1307,7 @@ locale_alias = { + 'hi': 'hi_IN.ISCII-DEV', + 'hi_in': 'hi_IN.ISCII-DEV', + 'hi_in.isciidev': 'hi_IN.ISCII-DEV', ++ 'hif_fj': 'hif_FJ.UTF-8', + 'hne': 'hne_IN.UTF-8', + 'hne_in': 'hne_IN.UTF-8', + 'hr': 'hr_HR.ISO8859-2', +@@ -1361,7 +1391,8 @@ locale_alias = { + 'ka_ge.georgianacademy': 'ka_GE.GEORGIAN-ACADEMY', + 'ka_ge.georgianps': 'ka_GE.GEORGIAN-PS', + 'ka_ge.georgianrs': 'ka_GE.GEORGIAN-ACADEMY', +- 'kk_kz': 'kk_KZ.RK1048', ++ 'kab_dz': 'kab_DZ.UTF-8', ++ 'kk_kz': 'kk_KZ.ptcp154', + 'kl': 'kl_GL.ISO8859-1', + 'kl_gl': 'kl_GL.ISO8859-1', + 'kl_gl.iso88591': 'kl_GL.ISO8859-1', +@@ -1379,6 +1410,7 @@ locale_alias = { + 'korean.euc': 'ko_KR.eucKR', + 'ks': 'ks_IN.UTF-8', + 'ks_in': 'ks_IN.UTF-8', ++ 'ks_in.utf8@devanagari': 'ks_IN.UTF-8@devanagari', + 'ks_in@devanagari': 'ks_IN.UTF-8@devanagari', + 'ks_in@devanagari.utf8': 'ks_IN.UTF-8@devanagari', + 'ku_tr': 'ku_TR.ISO8859-9', +@@ -1396,6 +1428,7 @@ locale_alias = { + 'li_nl': 'li_NL.UTF-8', + 'lij_it': 'lij_IT.UTF-8', + 'lithuanian': 'lt_LT.ISO8859-13', ++ 'ln_cd': 'ln_CD.UTF-8', + 'lo': 'lo_LA.MULELAO-1', + 'lo_la': 'lo_LA.MULELAO-1', + 'lo_la.cp1133': 'lo_LA.IBM-CP1133', +@@ -1409,14 +1442,19 @@ locale_alias = { + 'lv_lv': 'lv_LV.ISO8859-13', + 'lv_lv.iso885913': 'lv_LV.ISO8859-13', + 'lv_lv.iso88594': 'lv_LV.ISO8859-4', ++ 'lzh_tw': 'lzh_TW.UTF-8', + 'mag_in': 'mag_IN.UTF-8', + 'mai': 'mai_IN.UTF-8', + 'mai_in': 'mai_IN.UTF-8', ++ 'mai_np': 'mai_NP.UTF-8', ++ 'mfe_mu': 'mfe_MU.UTF-8', + 'mg_mg': 'mg_MG.ISO8859-15', + 'mhr_ru': 'mhr_RU.UTF-8', + 'mi': 'mi_NZ.ISO8859-1', + 'mi_nz': 'mi_NZ.ISO8859-1', + 'mi_nz.iso88591': 'mi_NZ.ISO8859-1', ++ 'miq_ni': 'miq_NI.UTF-8', ++ 'mjw_in': 'mjw_IN.UTF-8', + 'mk': 'mk_MK.ISO8859-5', + 'mk_mk': 'mk_MK.ISO8859-5', + 'mk_mk.cp1251': 'mk_MK.CP1251', +@@ -1435,7 +1473,7 @@ locale_alias = { + 'mt_mt': 'mt_MT.ISO8859-3', + 'mt_mt.iso88593': 'mt_MT.ISO8859-3', + 'my_mm': 'my_MM.UTF-8', +- 'nan_tw@latin': 'nan_TW.UTF-8@latin', ++ 'nan_tw': 'nan_TW.UTF-8', + 'nb': 'nb_NO.ISO8859-1', + 'nb_no': 'nb_NO.ISO8859-1', + 'nb_no.88591': 'nb_NO.ISO8859-1', +@@ -1509,6 +1547,8 @@ locale_alias = { + 'pa_in': 'pa_IN.UTF-8', + 'pa_pk': 'pa_PK.UTF-8', + 'pap_an': 'pap_AN.UTF-8', ++ 'pap_aw': 'pap_AW.UTF-8', ++ 'pap_cw': 'pap_CW.UTF-8', + 'pd': 'pd_US.ISO8859-1', + 'pd_de': 'pd_DE.ISO8859-1', + 'pd_de.iso88591': 'pd_DE.ISO8859-1', +@@ -1549,6 +1589,8 @@ locale_alias = { + 'pt_pt.iso885915@euro': 'pt_PT.ISO8859-15', + 'pt_pt.utf8@euro': 'pt_PT.UTF-8', + 'pt_pt@euro': 'pt_PT.ISO8859-15', ++ 'quz_pe': 'quz_PE.UTF-8', ++ 'raj_in': 'raj_IN.UTF-8', + 'ro': 'ro_RO.ISO8859-2', + 'ro_ro': 'ro_RO.ISO8859-2', + 'ro_ro.iso88592': 'ro_RO.ISO8859-2', +@@ -1565,7 +1607,7 @@ locale_alias = { + 'ru_ua.koi8u': 'ru_UA.KOI8-U', + 'ru_ua.microsoftcp1251': 'ru_UA.CP1251', + 'rumanian': 'ro_RO.ISO8859-2', +- 'russian': 'ru_RU.ISO8859-5', ++ 'russian': 'ru_RU.KOI8-R', + 'rw': 'rw_RW.ISO8859-1', + 'rw_rw': 'rw_RW.ISO8859-1', + 'rw_rw.iso88591': 'rw_RW.ISO8859-1', +@@ -1575,17 +1617,20 @@ locale_alias = { + 'sd': 'sd_IN.UTF-8', + 'sd@devanagari': 'sd_IN.UTF-8@devanagari', + 'sd_in': 'sd_IN.UTF-8', ++ 'sd_in.utf8@devanagari': 'sd_IN.UTF-8@devanagari', + 'sd_in@devanagari': 'sd_IN.UTF-8@devanagari', + 'sd_in@devanagari.utf8': 'sd_IN.UTF-8@devanagari', + 'sd_pk': 'sd_PK.UTF-8', + 'se_no': 'se_NO.UTF-8', + 'serbocroatian': 'sr_RS.UTF-8@latin', ++ 'sgs_lt': 'sgs_LT.UTF-8', + 'sh': 'sr_RS.UTF-8@latin', + 'sh_ba.iso88592@bosnia': 'sr_CS.ISO8859-2', + 'sh_hr': 'sh_HR.ISO8859-2', + 'sh_hr.iso88592': 'hr_HR.ISO8859-2', + 'sh_sp': 'sr_CS.ISO8859-2', + 'sh_yu': 'sr_RS.UTF-8@latin', ++ 'shn_mm': 'shn_MM.UTF-8', + 'shs_ca': 'shs_CA.UTF-8', + 'si': 'si_LK.UTF-8', + 'si_lk': 'si_LK.UTF-8', +@@ -1601,6 +1646,7 @@ locale_alias = { + 'slovak': 'sk_SK.ISO8859-2', + 'slovene': 'sl_SI.ISO8859-2', + 'slovenian': 'sl_SI.ISO8859-2', ++ 'sm_ws': 'sm_WS.UTF-8', + 'so_dj': 'so_DJ.ISO8859-1', + 'so_et': 'so_ET.UTF-8', + 'so_ke': 'so_KE.ISO8859-1', +@@ -1627,6 +1673,7 @@ locale_alias = { + 'sr_cs@latn': 'sr_CS.UTF-8@latin', + 'sr_me': 'sr_ME.UTF-8', + 'sr_rs': 'sr_RS.UTF-8', ++ 'sr_rs.utf8@latn': 'sr_RS.UTF-8@latin', + 'sr_rs@latin': 'sr_RS.UTF-8@latin', + 'sr_rs@latn': 'sr_RS.UTF-8@latin', + 'sr_sp': 'sr_CS.ISO8859-2', +@@ -1668,6 +1715,7 @@ locale_alias = { + 'ta_in.tscii': 'ta_IN.TSCII-0', + 'ta_in.tscii0': 'ta_IN.TSCII-0', + 'ta_lk': 'ta_LK.UTF-8', ++ 'tcy_in.utf8': 'tcy_IN.UTF-8', + 'te': 'te_IN.UTF-8', + 'te_in': 'te_IN.UTF-8', + 'tg': 'tg_TJ.KOI8-C', +@@ -1679,6 +1727,7 @@ locale_alias = { + 'th_th.tactis': 'th_TH.TIS620', + 'th_th.tis620': 'th_TH.TIS620', + 'thai': 'th_TH.ISO8859-11', ++ 'the_np': 'the_NP.UTF-8', + 'ti_er': 'ti_ER.UTF-8', + 'ti_et': 'ti_ET.UTF-8', + 'tig_er': 'tig_ER.UTF-8', +@@ -1689,6 +1738,8 @@ locale_alias = { + 'tn': 'tn_ZA.ISO8859-15', + 'tn_za': 'tn_ZA.ISO8859-15', + 'tn_za.iso885915': 'tn_ZA.ISO8859-15', ++ 'to_to': 'to_TO.UTF-8', ++ 'tpi_pg': 'tpi_PG.UTF-8', + 'tr': 'tr_TR.ISO8859-9', + 'tr_cy': 'tr_CY.ISO8859-9', + 'tr_tr': 'tr_TR.ISO8859-9', +@@ -1750,6 +1801,7 @@ locale_alias = { + 'yi_us.microsoftcp1255': 'yi_US.CP1255', + 'yo_ng': 'yo_NG.UTF-8', + 'yue_hk': 'yue_HK.UTF-8', ++ 'yuw_pg': 'yuw_PG.UTF-8', + 'zh': 'zh_CN.eucCN', + 'zh_cn': 'zh_CN.gb2312', + 'zh_cn.big5': 'zh_TW.big5', +diff --git a/Lib/multiprocessing/managers.py b/Lib/multiprocessing/managers.py +index f2cee0c38c..118812c8ce 100644 +--- a/Lib/multiprocessing/managers.py ++++ b/Lib/multiprocessing/managers.py +@@ -1059,10 +1059,13 @@ class ListProxy(BaseListProxy): + + + DictProxy = MakeProxyType('DictProxy', ( +- '__contains__', '__delitem__', '__getitem__', '__len__', ++ '__contains__', '__delitem__', '__getitem__', '__iter__', '__len__', + '__setitem__', 'clear', 'copy', 'get', 'has_key', 'items', + 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values' + )) ++DictProxy._method_to_typeid_ = { ++ '__iter__': 'Iterator', ++ } + + + ArrayProxy = MakeProxyType('ArrayProxy', ( +diff --git a/Lib/pickletools.py b/Lib/pickletools.py +index c9366c8ce3..cc15540e55 100644 +--- a/Lib/pickletools.py ++++ b/Lib/pickletools.py +@@ -1048,9 +1048,7 @@ opcodes = [ + stack_before=[], + stack_after=[pybool], + proto=2, +- doc="""True. +- +- Push True onto the stack."""), ++ doc="Push True onto the stack."), + + I(name='NEWFALSE', + code='\x89', +@@ -1058,9 +1056,7 @@ opcodes = [ + stack_before=[], + stack_after=[pybool], + proto=2, +- doc="""True. +- +- Push False onto the stack."""), ++ doc="Push False onto the stack."), + + # Ways to spell Unicode strings. + +diff --git a/Lib/platform.py b/Lib/platform.py +index 55f2fa8995..62a5476a8f 100755 +--- a/Lib/platform.py ++++ b/Lib/platform.py +@@ -132,6 +132,35 @@ except AttributeError: + # Standard Unix uses /dev/null + DEV_NULL = '/dev/null' + ++# Helper for comparing two version number strings. ++# Based on the description of the PHP's version_compare(): ++# http://php.net/manual/en/function.version-compare.php ++ ++_ver_stages = { ++ # any string not found in this dict, will get 0 assigned ++ 'dev': 10, ++ 'alpha': 20, 'a': 20, ++ 'beta': 30, 'b': 30, ++ 'c': 40, ++ 'RC': 50, 'rc': 50, ++ # number, will get 100 assigned ++ 'pl': 200, 'p': 200, ++} ++ ++_component_re = re.compile(r'([0-9]+|[._+-])') ++ ++def _comparable_version(version): ++ result = [] ++ for v in _component_re.split(version): ++ if v not in '._+-': ++ try: ++ v = int(v, 10) ++ t = 100 ++ except ValueError: ++ t = _ver_stages.get(v, 0) ++ result.extend((t, v)) ++ return result ++ + ### Platform specific APIs + + _libc_search = re.compile(r'(__libc_init)' +@@ -140,9 +169,7 @@ _libc_search = re.compile(r'(__libc_init)' + '|' + '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)') + +-def libc_ver(executable=sys.executable,lib='',version='', +- +- chunksize=2048): ++def libc_ver(executable=sys.executable,lib='',version='', chunksize=2048): + + """ Tries to determine the libc version that the file executable + (which defaults to the Python interpreter) is linked against. +@@ -157,40 +184,42 @@ def libc_ver(executable=sys.executable,lib='',version='', + The file is read and scanned in chunks of chunksize bytes. + + """ ++ V = _comparable_version + if hasattr(os.path, 'realpath'): + # Python 2.2 introduced os.path.realpath(); it is used + # here to work around problems with Cygwin not being + # able to open symlinks for reading + executable = os.path.realpath(executable) +- f = open(executable,'rb') +- binary = f.read(chunksize) +- pos = 0 +- while 1: +- m = _libc_search.search(binary,pos) +- if not m: +- binary = f.read(chunksize) +- if not binary: +- break +- pos = 0 +- continue +- libcinit,glibc,glibcversion,so,threads,soversion = m.groups() +- if libcinit and not lib: +- lib = 'libc' +- elif glibc: +- if lib != 'glibc': +- lib = 'glibc' +- version = glibcversion +- elif glibcversion > version: +- version = glibcversion +- elif so: +- if lib != 'glibc': ++ with open(executable, 'rb') as f: ++ binary = f.read(chunksize) ++ pos = 0 ++ while pos < len(binary): ++ m = _libc_search.search(binary,pos) ++ if not m or m.end() == len(binary): ++ chunk = f.read(chunksize) ++ if chunk: ++ binary = binary[max(pos, len(binary) - 1000):] + chunk ++ pos = 0 ++ continue ++ if not m: ++ break ++ libcinit,glibc,glibcversion,so,threads,soversion = m.groups() ++ if libcinit and not lib: + lib = 'libc' +- if soversion and soversion > version: +- version = soversion +- if threads and version[-len(threads):] != threads: +- version = version + threads +- pos = m.end() +- f.close() ++ elif glibc: ++ if lib != 'glibc': ++ lib = 'glibc' ++ version = glibcversion ++ elif V(glibcversion) > V(version): ++ version = glibcversion ++ elif so: ++ if lib != 'glibc': ++ lib = 'libc' ++ if soversion and (not version or V(soversion) > V(version)): ++ version = soversion ++ if threads and version[-len(threads):] != threads: ++ version = version + threads ++ pos = m.end() + return lib,version + + def _dist_try_harder(distname,version,id): +@@ -451,6 +480,7 @@ def popen(cmd, mode='r', bufsize=None): + else: + return popen(cmd,mode,bufsize) + ++ + def _norm_version(version, build=''): + + """ Normalize the version and build strings and return a single +diff --git a/Lib/pydoc.py b/Lib/pydoc.py +index b4b190f3f9..62cc262ccb 100755 +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -1647,8 +1647,9 @@ class Helper: + } + # Either add symbols to this dictionary or to the symbols dictionary + # directly: Whichever is easier. They are merged later. ++ _strprefixes = tuple(p + q for p in ('b', 'r', 'u') for q in ("'", '"')) + _symbols_inverse = { +- 'STRINGS' : ("'", "'''", "r'", "u'", '"""', '"', 'r"', 'u"'), ++ 'STRINGS' : ("'", "'''", '"""', '"') + _strprefixes, + 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&', + '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'), + 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'), +@@ -1811,7 +1812,12 @@ has the same effect as typing a particular string at the help> prompt. + if not request: break + except (KeyboardInterrupt, EOFError): + break +- request = strip(replace(request, '"', '', "'", '')) ++ request = strip(request) ++ # Make sure significant trailing quotation marks of literals don't ++ # get deleted while cleaning input ++ if (len(request) > 2 and request[0] == request[-1] in ("'", '"') ++ and request[0] not in request[1:-1]): ++ request = request[1:-1] + if lower(request) in ('q', 'quit'): break + self.help(request) + +diff --git a/Lib/robotparser.py b/Lib/robotparser.py +index a7137a3064..4e13f7f780 100644 +--- a/Lib/robotparser.py ++++ b/Lib/robotparser.py +@@ -160,7 +160,10 @@ class RobotFileParser: + + + def __str__(self): +- return ''.join([str(entry) + "\n" for entry in self.entries]) ++ entries = self.entries ++ if self.default_entry is not None: ++ entries = entries + [self.default_entry] ++ return '\n'.join(map(str, entries)) + '\n' + + + class RuleLine: +diff --git a/Lib/shutil.py b/Lib/shutil.py +index 3462f7c5e9..0ab1a06f52 100644 +--- a/Lib/shutil.py ++++ b/Lib/shutil.py +@@ -413,17 +413,21 @@ def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, + + return archive_name + +-def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False): ++def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger): + # XXX see if we want to keep an external call here + if verbose: + zipoptions = "-r" + else: + zipoptions = "-rq" +- from distutils.errors import DistutilsExecError +- from distutils.spawn import spawn ++ cmd = ["zip", zipoptions, zip_filename, base_dir] ++ if logger is not None: ++ logger.info(' '.join(cmd)) ++ if dry_run: ++ return ++ import subprocess + try: +- spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run) +- except DistutilsExecError: ++ subprocess.check_call(cmd) ++ except subprocess.CalledProcessError: + # XXX really should distinguish between "couldn't find + # external 'zip' command" and "zip failed". + raise ExecError, \ +@@ -458,7 +462,7 @@ def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): + zipfile = None + + if zipfile is None: +- _call_external_zip(base_dir, zip_filename, verbose, dry_run) ++ _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger) + else: + if logger is not None: + logger.info("creating '%s' and adding '%s' to it", +diff --git a/Lib/test/allsans.pem b/Lib/test/allsans.pem +index 3ee4f59513..6eebde7a57 100644 +--- a/Lib/test/allsans.pem ++++ b/Lib/test/allsans.pem +@@ -1,37 +1,81 @@ + -----BEGIN PRIVATE KEY----- +-MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOoy7/QOtTjQ0niE +-6uDcTwtkC0R2Tvy1AjVnXohCntZfdzbTGDoYTgXSOLsP8A697jUiJ8VCePGH50xG +-Z4DKnAF3a9O3a9nr2pLXb0iY3XOMv+YEBii7CfI+3oxFYgCl0sMgHzDD2ZTVYAsm +-DWgLUVsE2gHEccRwrM2tPf2EgR+FAgMBAAECgYEA3qyfyYVSeTrTYxO93x6ZaVMu +-A2IZp9zSxMQL9bKiI2GRj+cV2ebSCGbg2btFnD6qBor7FWsmYz+8g6FNN/9sY4az +-61rMqMtQvLBe+7L8w70FeTze4qQ4Y1oQri0qD6tBWhDVlpnbI5Py9bkZKD67yVUk +-elcEA/5x4PrYXkuqsAECQQD80NjT0mDvaY0JOOaQFSEpMv6QiUA8GGX8Xli7IoKb +-tAolPG8rQBa+qSpcWfDMTrWw/aWHuMEEQoP/bVDH9W4FAkEA7SYQbBAKnojZ5A3G +-kOHdV7aeivRQxQk/JN8Fb8oKB9Csvpv/BsuGxPKXHdhFa6CBTTsNRtHQw/szPo4l +-xMIjgQJAPoMxqibR+0EBM6+TKzteSL6oPXsCnBl4Vk/J5vPgkbmR7KUl4+7j8N8J +-b2554TrxKEN/w7CGYZRE6UrRd7ATNQJAWD7Yz41sli+wfPdPU2xo1BHljyl4wMk/ +-EPZYbI/PCbdyAH/F935WyQTIjNeEhZc1Zkq6FwdOWw8ns3hrv3rKgQJAHXv1BqUa +-czGPIFxX2TNoqtcl6/En4vrxVB1wzsfzkkDAg98kBl7qsF+S3qujSzKikjeaVbI2 +-/CyWR2P3yLtOmA== ++MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQCg/pM6dP7BTFNc ++qe6wIJIBB7HjwL42bp0vjcCVl4Z3MRWFswYpfxy+o+8+PguMp4K6zndA5fwNkK/H ++3HmtanncUfPqnV0usN0NHQGh/f9xRoNmB1q2L7kTuO99o0KLQgvonRT2snf8rq9n ++tPRzhHUGYhog7zzNxetYV309PHpPr19BcKepDtM5RMk2aBnoN5vtItorjXiDosFm ++6o5wQHrcupcVydszba6P75BEbc1XIWvq2Fv8muaw4pCe81QYINyLqgcPNO/nF3Os ++5EI4HKjCNRSCOhOcWqYctXLXN9lBdMBBvQc3zDmYzh1eIZewzZXPVEQT33xPkhxz ++HNmhcIctpWX4LTRF6FulkcbeuZDga3gkZYJf/M6IpU1WYXr6q8sNxbgmRRX/NuHo ++V9oDwBzLG07rKUiqRHfjGqoCRmmVeVYpryvXUNjHGH0nlVzz/8lTUxAnJorO3Fdc ++I+6zKLUPICdAlvz51AH6yopgPFhrdgA0pVzPO6L5G8SRQCxKhAUCAwEAAQKCAYAa ++2jtOTcNMFGH3G7TfFZ+kolbuaPCQ/aQkEV2k1dAswzgWw8RsWXI+7fLyi8C7Zhks ++9VD4tyNyU8at7D0zSoYm1Fh9sl+fcQp9rG/gSBA6IYu7EdD0gEM7YeY4K2nm9k4s ++Lz8W4q+WqsBA6PK47cfjF6vKAH1AyRk28+jEtPiln9egf5zHWtyqOanh9D0V+Wh9 ++hgmjqAYI1rWxZ7/4Qxj7Bfg7Px7blhi+kzOZ5kKQnNd2JT46hM+jgzah/G3zVE+R ++FFW6ksmJgZ+dCuSbE7HEJmKms1CWq/1Cll0A3uy4JTDZOrK4KcZQ9UjjWJWvlXQm ++uNXSSAp1k287DLVUm9c22SDeXpb9PyKmzyvJvVmMqqBx6QzHZ/L7WPzpUWAoLcU+ ++ZHT7vggDymkIO+fcRbUzv8s5R7RnLbcBga51/5OCUvAWDoJXNw0qwYZOIbfTnQgs ++8xbCmbMzllyYM/dK3GxQAwfn8Hzk+DbS/NObMjHLCWLfYeUvutXJSNly6Ny+ZcEC ++gcEAzo5Y1UFOfBX4MZLIZ69LfgaXj9URobMwqlEwKil8pWQMa951ga3moLt91nOe ++SAQz3meFTBX/VAb2ZHLeIf3FoNkiIx48PkxsR/hhLHpvl26zEg3yXs3tv0IFBx2R ++EEnLNpQaAQFR9S1yDOaG2rsb17ZDKyp9isDpAENHAmEnT/XJn+Dc0SOH1EVDjUeM ++JqToAF/fjIx/RF4oUJCAgOPBMlRy5ywLQk8uDi6ft0NCzzCi0eCuk1Ty3KzWFGwx ++7cYRAoHBAMeIPCzHG3No4JGUFunslVwo5TuC7maO6qYKbq0OyvwWfL4b7gjrMBR9 ++d5WyZlp/Vf40O463dg8x8qPNOFWp49f3hxTvvfnt2/m3+CQuDOLfqBbHufZApP1J ++U9MubUNnDFHHeJ9l0tg2nhiLw24GHeMARZhA/BimMQPY0OpZPpLVxAUArM2EB7hI ++glQpYCtdXhqwl1pl0u3TZ08y3BXYNg9BycdpGRMWSsAwsApJRgNuI/dfDKu0uMYF ++/pUhXVPatQKBwGgLpAun3dT7bA3sli5ESo6s22OEPGFrVbQ1OUHDrBnTj742TJKJ +++oY0a2q+ypgUJdx94NM2sWquJybqBaKxpf8j4OI3tLjc3h5SqwAwnE13YZRSmifP ++K1cP9mBjMFM4GLjhWUfwVkxeG/kLlhpP7fJ2yNbRjHN8QOH1AavdLGRGts1mA1UF ++xMHUMfbUd3Bv2L13ja/KhcD2fPA4GcLS9tpXV5nCwdkg8V4LdkBmDR04rotx1f44 ++6Czokt2usmfHQQKBwFkufxbUd2SB/72Rnxw27hse/DY5My0Lu70y9HzNG9TIiEDA ++YwgBdp/x5D04W58fQuQ3nFcRkOcBwB2OYBuJr5ibvfiRnyvSMHvQykwBeSj+Jjbo ++VinGgvfiimDdY2C48jyrFzLHZBHXd5oo/dRzT3Bicri2cvbhcQ7zHY1hDiK7AL3r ++q1DALmMjpXzQcXdwZ9suCrgQwtIhpw8zAEOTO7ZeBT3nr5lkYUy9djFixrRJyjGK ++fjNQtzVrAHrPStNr8QKBwQDCC0zhsCnTv4sAJmW7LL6Ayd5rbWhUZ6px1xY0yHMA ++hehj+xbaiC6cfVr5Rg0ncvaa8AExu4kXpVsupTyNwvC4NgzLHtfBw6WUdOnd1awE ++kSrDtDReBt2wByAcQwttQsrJ1/Pt6zcNJJI4Z9s8G4NTcQWJwUhU20N55JQKR//l ++OQJqhq9NVhte/ctDjVwOHs/OhDNvxsAWxdjnf/O2up0os+M2bFkmHuaVW0vQbqTQ ++mw7Vbzk2Ff5oT6E3kbC8Ur4= + -----END PRIVATE KEY----- + -----BEGIN CERTIFICATE----- +-MIIDcjCCAtugAwIBAgIJAN5dc9TOWjB7MA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV ++MIIHMDCCBZigAwIBAgIJALVVA6v9zJS5MA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV + BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u +-IFNvZnR3YXJlIEZvdW5kYXRpb24xEDAOBgNVBAMMB2FsbHNhbnMwHhcNMTYwODA1 +-MTAyMTExWhcNMjYwODAzMTAyMTExWjBdMQswCQYDVQQGEwJYWTEXMBUGA1UEBwwO ++IFNvZnR3YXJlIEZvdW5kYXRpb24xEDAOBgNVBAMMB2FsbHNhbnMwHhcNMTgwODI5 ++MTQyMzE3WhcNMjgwODI2MTQyMzE3WjBdMQswCQYDVQQGEwJYWTEXMBUGA1UEBwwO + Q2FzdGxlIEFudGhyYXgxIzAhBgNVBAoMGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0 +-aW9uMRAwDgYDVQQDDAdhbGxzYW5zMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB +-gQDqMu/0DrU40NJ4hOrg3E8LZAtEdk78tQI1Z16IQp7WX3c20xg6GE4F0ji7D/AO +-ve41IifFQnjxh+dMRmeAypwBd2vTt2vZ69qS129ImN1zjL/mBAYouwnyPt6MRWIA +-pdLDIB8ww9mU1WALJg1oC1FbBNoBxHHEcKzNrT39hIEfhQIDAQABo4IBODCCATQw +-ggEwBgNVHREEggEnMIIBI4IHYWxsc2Fuc6AeBgMqAwSgFwwVc29tZSBvdGhlciBp +-ZGVudGlmaWVyoDUGBisGAQUCAqArMCmgEBsOS0VSQkVST1MuUkVBTE2hFTAToAMC +-AQGhDDAKGwh1c2VybmFtZYEQdXNlckBleGFtcGxlLm9yZ4IPd3d3LmV4YW1wbGUu +-b3JnpGcwZTELMAkGA1UEBhMCWFkxFzAVBgNVBAcMDkNhc3RsZSBBbnRocmF4MSMw +-IQYDVQQKDBpQeXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEYMBYGA1UEAwwPZGly +-bmFtZSBleGFtcGxlhhdodHRwczovL3d3dy5weXRob24ub3JnL4cEfwAAAYcQAAAA +-AAAAAAAAAAAAAAAAAYgEKgMEBTANBgkqhkiG9w0BAQsFAAOBgQAy16h+F+nOmeiT +-VWR0fc8F/j6FcadbLseAUaogcC15OGxCl4UYpLV88HBkABOoGCpP155qwWTwOrdG +-iYPGJSusf1OnJEbvzFejZf6u078bPd9/ZL4VWLjv+FPGkjd+N+/OaqMvgj8Lu99f +-3Y/C4S7YbHxxwff6C6l2Xli+q6gnuQ== ++aW9uMRAwDgYDVQQDDAdhbGxzYW5zMIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIB ++igKCAYEAoP6TOnT+wUxTXKnusCCSAQex48C+Nm6dL43AlZeGdzEVhbMGKX8cvqPv ++Pj4LjKeCus53QOX8DZCvx9x5rWp53FHz6p1dLrDdDR0Bof3/cUaDZgdati+5E7jv ++faNCi0IL6J0U9rJ3/K6vZ7T0c4R1BmIaIO88zcXrWFd9PTx6T69fQXCnqQ7TOUTJ ++NmgZ6Deb7SLaK414g6LBZuqOcEB63LqXFcnbM22uj++QRG3NVyFr6thb/JrmsOKQ ++nvNUGCDci6oHDzTv5xdzrORCOByowjUUgjoTnFqmHLVy1zfZQXTAQb0HN8w5mM4d ++XiGXsM2Vz1REE998T5IccxzZoXCHLaVl+C00RehbpZHG3rmQ4Gt4JGWCX/zOiKVN ++VmF6+qvLDcW4JkUV/zbh6FfaA8AcyxtO6ylIqkR34xqqAkZplXlWKa8r11DYxxh9 ++J5Vc8//JU1MQJyaKztxXXCPusyi1DyAnQJb8+dQB+sqKYDxYa3YANKVczzui+RvE ++kUAsSoQFAgMBAAGjggLxMIIC7TCCATAGA1UdEQSCAScwggEjggdhbGxzYW5zoB4G ++AyoDBKAXDBVzb21lIG90aGVyIGlkZW50aWZpZXKgNQYGKwYBBQICoCswKaAQGw5L ++RVJCRVJPUy5SRUFMTaEVMBOgAwIBAaEMMAobCHVzZXJuYW1lgRB1c2VyQGV4YW1w ++bGUub3Jngg93d3cuZXhhbXBsZS5vcmekZzBlMQswCQYDVQQGEwJYWTEXMBUGA1UE ++BwwOQ2FzdGxlIEFudGhyYXgxIzAhBgNVBAoMGlB5dGhvbiBTb2Z0d2FyZSBGb3Vu ++ZGF0aW9uMRgwFgYDVQQDDA9kaXJuYW1lIGV4YW1wbGWGF2h0dHBzOi8vd3d3LnB5 ++dGhvbi5vcmcvhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABiAQqAwQFMA4GA1UdDwEB ++/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/ ++BAIwADAdBgNVHQ4EFgQUoLHAHNTWrHkSCUYkhn5NH0S40CAwgY8GA1UdIwSBhzCB ++hIAUoLHAHNTWrHkSCUYkhn5NH0S40CChYaRfMF0xCzAJBgNVBAYTAlhZMRcwFQYD ++VQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9uIFNvZnR3YXJlIEZv ++dW5kYXRpb24xEDAOBgNVBAMMB2FsbHNhbnOCCQC1VQOr/cyUuTCBgwYIKwYBBQUH ++AQEEdzB1MDwGCCsGAQUFBzAChjBodHRwOi8vdGVzdGNhLnB5dGhvbnRlc3QubmV0 ++L3Rlc3RjYS9weWNhY2VydC5jZXIwNQYIKwYBBQUHMAGGKWh0dHA6Ly90ZXN0Y2Eu ++cHl0aG9udGVzdC5uZXQvdGVzdGNhL29jc3AvMEMGA1UdHwQ8MDowOKA2oDSGMmh0 ++dHA6Ly90ZXN0Y2EucHl0aG9udGVzdC5uZXQvdGVzdGNhL3Jldm9jYXRpb24uY3Js ++MA0GCSqGSIb3DQEBCwUAA4IBgQAeKJKycO2DES98gyR2e/GzPYEw87cCS0cEpiiP ++3CEUgzfEbF0X89GDKEey4H3Irvosbvt2hEcf2RNpahLUL/fUv53bDmHNmL8qJg5E ++UJVMOHvOpSOjqoqeRuSyG0GnnAuUwcxdrZY6UzLdslhuq9F8UjgHr6KSMx56G9uK ++LmTy5njMab0in2xL/YRX/0nogK3BHqpUHrfCdEYZkciRxtAa+OPpWn4dcZi+Fpf7 ++ZYSgPLNt+djtFDMIAk5Bo+XDaQdW3dhF0w44enrGAOV0xPE+/jOuenNhKBafjuNb ++lkeSr45+QZsi1rd18ny8z3uuaGqIAziFgmllZOH2D8giTn6+5jZcCNZCoGKUkPI9 ++l/GMWwxg4HQYYlZcsZzTCem9Rb2XcrasAbmhFapMtR+QAwSed5vKE7ZdtQhj74kB ++7Q0E7Lkgpp6BaObb2As8/f0K/UlSVSvrYk+i3JT9wK/qqkRGxsTFEF7N9t0rKu8y ++4JdQDtZCI552MsFvYW6m+IOYgxg= + -----END CERTIFICATE----- +diff --git a/Lib/test/bisect.py b/Lib/test/bisect_cmd.py +similarity index 100% +rename from Lib/test/bisect.py +diff --git a/Lib/test/crashers/warnings_del_crasher.py b/Lib/test/crashers/warnings_del_crasher.py +diff --git a/Lib/test/crashers/warnings_del_crasher.py b/Lib/test/crashers/warnings_del_crasher.py +new file mode 100644 +index 0000000000..02e6805202 +--- /dev/null ++++ b/Lib/test/crashers/warnings_del_crasher.py +@@ -0,0 +1,29 @@ ++""" ++Expose a race in the _warnings module, which is the C backend for the ++warnings module. The "_warnings" module tries to access attributes of the ++"warnings" module (because of the API it has to support), but doing so ++during interpreter shutdown is problematic. Specifically, the call to ++PyImport_GetModuleDict() in Python/_warnings.c:get_warnings_attr will ++abort() if the modules dict has already been cleaned up. ++ ++This crasher is timing-dependent, and more threads (NUM_THREADS) may be ++necessary to expose it reliably on different systems. ++""" ++ ++import threading ++import warnings ++ ++NUM_THREADS = 10 ++ ++class WarnOnDel(object): ++ def __del__(self): ++ warnings.warn("oh no something went wrong", UserWarning) ++ ++def do_work(): ++ while True: ++ w = WarnOnDel() ++ ++for i in range(NUM_THREADS): ++ t = threading.Thread(target=do_work) ++ t.setDaemon(1) ++ t.start() +diff --git a/Lib/test/dh1024.pem b/Lib/test/dh1024.pem +deleted file mode 100644 +index a391176b5f..0000000000 ++++ /dev/null +@@ -1,7 +0,0 @@ +------BEGIN DH PARAMETERS----- +-MIGHAoGBAIbzw1s9CT8SV5yv6L7esdAdZYZjPi3qWFs61CYTFFQnf2s/d09NYaJt +-rrvJhIzWavqnue71qXCf83/J3nz3FEwUU/L0mGyheVbsSHiI64wUo3u50wK5Igo0 +-RNs/LD0irs7m0icZ//hijafTU+JOBiuA8zMI+oZfU7BGuc9XrUprAgEC +------END DH PARAMETERS----- +- +-Generated with: openssl dhparam -out dh1024.pem 1024 +diff --git a/Lib/test/ffdh3072.pem b/Lib/test/ffdh3072.pem +new file mode 100644 +index 0000000000..ad69bac8d0 +--- /dev/null ++++ b/Lib/test/ffdh3072.pem +@@ -0,0 +1,41 @@ ++ DH Parameters: (3072 bit) ++ prime: ++ 00:ff:ff:ff:ff:ff:ff:ff:ff:ad:f8:54:58:a2:bb: ++ 4a:9a:af:dc:56:20:27:3d:3c:f1:d8:b9:c5:83:ce: ++ 2d:36:95:a9:e1:36:41:14:64:33:fb:cc:93:9d:ce: ++ 24:9b:3e:f9:7d:2f:e3:63:63:0c:75:d8:f6:81:b2: ++ 02:ae:c4:61:7a:d3:df:1e:d5:d5:fd:65:61:24:33: ++ f5:1f:5f:06:6e:d0:85:63:65:55:3d:ed:1a:f3:b5: ++ 57:13:5e:7f:57:c9:35:98:4f:0c:70:e0:e6:8b:77: ++ e2:a6:89:da:f3:ef:e8:72:1d:f1:58:a1:36:ad:e7: ++ 35:30:ac:ca:4f:48:3a:79:7a:bc:0a:b1:82:b3:24: ++ fb:61:d1:08:a9:4b:b2:c8:e3:fb:b9:6a:da:b7:60: ++ d7:f4:68:1d:4f:42:a3:de:39:4d:f4:ae:56:ed:e7: ++ 63:72:bb:19:0b:07:a7:c8:ee:0a:6d:70:9e:02:fc: ++ e1:cd:f7:e2:ec:c0:34:04:cd:28:34:2f:61:91:72: ++ fe:9c:e9:85:83:ff:8e:4f:12:32:ee:f2:81:83:c3: ++ fe:3b:1b:4c:6f:ad:73:3b:b5:fc:bc:2e:c2:20:05: ++ c5:8e:f1:83:7d:16:83:b2:c6:f3:4a:26:c1:b2:ef: ++ fa:88:6b:42:38:61:1f:cf:dc:de:35:5b:3b:65:19: ++ 03:5b:bc:34:f4:de:f9:9c:02:38:61:b4:6f:c9:d6: ++ e6:c9:07:7a:d9:1d:26:91:f7:f7:ee:59:8c:b0:fa: ++ c1:86:d9:1c:ae:fe:13:09:85:13:92:70:b4:13:0c: ++ 93:bc:43:79:44:f4:fd:44:52:e2:d7:4d:d3:64:f2: ++ e2:1e:71:f5:4b:ff:5c:ae:82:ab:9c:9d:f6:9e:e8: ++ 6d:2b:c5:22:36:3a:0d:ab:c5:21:97:9b:0d:ea:da: ++ 1d:bf:9a:42:d5:c4:48:4e:0a:bc:d0:6b:fa:53:dd: ++ ef:3c:1b:20:ee:3f:d5:9d:7c:25:e4:1d:2b:66:c6: ++ 2e:37:ff:ff:ff:ff:ff:ff:ff:ff ++ generator: 2 (0x2) ++ recommended-private-length: 276 bits ++-----BEGIN DH PARAMETERS----- ++MIIBjAKCAYEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz +++8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a ++87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7 ++YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi ++7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD ++ssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3 ++7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32 ++nuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZsYu ++N///////////AgECAgIBFA== ++-----END DH PARAMETERS----- +diff --git a/Lib/test/inspect_fodder.py b/Lib/test/inspect_fodder.py +index 5c87ae6f82..548765c797 100644 +--- a/Lib/test/inspect_fodder.py ++++ b/Lib/test/inspect_fodder.py +@@ -56,3 +56,9 @@ class ParrotDroppings: + + class FesteringGob(MalodorousPervert, ParrotDroppings): + pass ++ ++currentframe = inspect.currentframe() ++try: ++ raise Exception() ++except: ++ tb = sys.exc_info()[2] +diff --git a/Lib/test/keycert.passwd.pem b/Lib/test/keycert.passwd.pem +index e90574881d..cbb3c3bccd 100644 +--- a/Lib/test/keycert.passwd.pem ++++ b/Lib/test/keycert.passwd.pem +@@ -1,33 +1,68 @@ + -----BEGIN RSA PRIVATE KEY----- + Proc-Type: 4,ENCRYPTED +-DEK-Info: DES-EDE3-CBC,1A8D9D2A02EC698A ++DEK-Info: DES-EDE3-CBC,D134E931C96D9DEC + +-kJYbfZ8L0sfe9Oty3gw0aloNnY5E8fegRfQLZlNoxTl6jNt0nIwI8kDJ36CZgR9c +-u3FDJm/KqrfUoz8vW+qEnWhSG7QPX2wWGPHd4K94Yz/FgrRzZ0DoK7XxXq9gOtVA +-AVGQhnz32p+6WhfGsCr9ArXEwRZrTk/FvzEPaU5fHcoSkrNVAGX8IpSVkSDwEDQr +-Gv17+cfk99UV1OCza6yKHoFkTtrC+PZU71LomBabivS2Oc4B9hYuSR2hF01wTHP+ +-YlWNagZOOVtNz4oKK9x9eNQpmfQXQvPPTfusexKIbKfZrMvJoxcm1gfcZ0H/wK6P +-6wmXSG35qMOOztCZNtperjs1wzEBXznyK8QmLcAJBjkfarABJX9vBEzZV0OUKhy+ +-noORFwHTllphbmydLhu6ehLUZMHPhzAS5UN7srtpSN81eerDMy0RMUAwA7/PofX1 +-94Me85Q8jP0PC9ETdsJcPqLzAPETEYu0ELewKRcrdyWi+tlLFrpE5KT/s5ecbl9l +-7B61U4Kfd1PIXc/siINhU3A3bYK+845YyUArUOnKf1kEox7p1RpD7yFqVT04lRTo +-cibNKATBusXSuBrp2G6GNuhWEOSafWCKJQAzgCYIp6ZTV2khhMUGppc/2H3CF6cO +-zX0KtlPVZC7hLkB6HT8SxYUwF1zqWY7+/XPPdc37MeEZ87Q3UuZwqORLY+Z0hpgt +-L5JXBCoklZhCAaN2GqwFLXtGiRSRFGY7xXIhbDTlE65Wv1WGGgDLMKGE1gOz3yAo +-2jjG1+yAHJUdE69XTFHSqSkvaloA1W03LdMXZ9VuQJ/ySXCie6ABAQ== ++nuGFEej7vIjkYWSMz5OJeVTNntDRQi6ZM4DBm3g8T7i/0odr3WFqGMMKZcIhLYQf ++rgRq7RSKtrJ1y5taVucMV+EuCjyfzDo0TsYt+ZrXv/D08eZhjRmkhoHnGVF0TqQm ++nQEXM/ERT4J2RM78dnG+homMkI76qOqxgGbRqQqJo6AiVRcAZ45y8s96bru2TAB8 +++pWjO/v0Je7AFVdwSU52N8OOY6uoSAygW+0UY1WVxbVGJF2XfRsNpPX+YQHYl6e+ ++3xM5XBVCgr6kmdAyub5qUJ38X3TpdVGoR0i+CVS9GTr2pSRib1zURAeeHnlqiUZM ++4m0Gn9s72nJevU1wxED8pwOhR8fnHEmMKGD2HPhKoOCbzDhwwBZO27TNa1uWeM3f ++M5oixKDi2PqMn3y2cDx1NjJtP661688EcJ5a2Ih9BgO9xpnhSyzBWEKcAn0tJB0H ++/56M0FW6cdOOIzMveGGL7sHW5E+iOdI1n5e7C6KJUzew78Y9qJnhS53EdI6qTz9R ++wsIsj1i070Fk6RbPo6zpLlF6w7Zj8GlZaZA7OZZv9wo5VEV/0ST8gmiiBOBc4C6Y ++u9hyLIIu4dFEBKyQHRvBnQSLNpKx6or1OGFDVBay2In9Yh2BHh1+vOj/OIz/wq48 ++EHOIV27fRJxLu4jeK5LIGDhuPnMJ8AJYQ0bQOUP6fd7p+TxWkAQZPB/Dx/cs3hxr ++nFEdzx+eO+IAsObx/b1EGZyEJyETBslu4GwYX7/KK3HsJhDJ1bdZ//28jOCaoir6 ++ZOMT72GRwmVoQTJ0XpccfjHfKJDRLT7C1xvzo4Eibth0hpTZkA75IUYUp6qK/PuJ ++kH/qdiC7QIkRKtsrawW4vEDna3YtxIYhQqz9+KwO6u/0gzooZtv1RU4U3ifMDB5u ++5P5GAzACRqlY8QYBkM869lvWqzQPHvybC4ak9Yx6/heMO9ddjdIW9BaK8BLxvN/6 ++UCD936Y4fWltt09jHZIoxWFykouBwmd7bXooNYXmDRNmjTdVhKJuOEOQw8hDzx7e ++pWFJ9Z/V4Qm1tvXbCD7QFqMCDoY3qFvVG8DBqXpmxe1yPfz21FWrT7IuqDXAD3ns ++vxfN/2a+Cy04U9FBNVCvWqWIs5AgNpdCMJC2FlXKTy+H3/7rIjNyFyvbX0vxIXtK ++liOVNXiyVM++KZXqktqMUDlsJENmIHV9B046luqbgW018fHkyEYlL3iRZGbYegwr ++XO9VVIKVPw1BEvJ8VNdGFGuZGepd8qX2ezfYADrNR+4t85HDm8inbjTobSjWuljs ++ftUNkOeCHqAvWCFQTLCfdykvV08EJfVY79y7yFPtfRV2gxYokXFifjo3su9sVQr1 ++UiIS5ZAsIC1hBXWeXoBN7QVTkFi7Yto6E1q2k10LiT3obpUUUQ/oclhrJOCJVjrS ++oRcj2QBy8OT4T9slJr5maTWdgd7Lt6+I6cGQXPaDvjGOJl0eBYM14vhx4rRQWytJ ++k07hhHFO4+9CGCuHS8AAy2gR6acYFWt2ZiiNZ0z/iPIHNK4YEyy9aLf6uZH/KQjE ++jmHToo7XD6QvCAEC5qTHby3o3LfHIhyZi/4L+AhS4FKUHF6M0peeyYt4z3HaK2d2 ++N6mHLPdjwNjra7GOmcns4gzcrdfoF+R293KpPal4PjknvR3dZL4kKP/ougTAM5zv ++qDIvRbkHzjP8ChTpoLcJsNVXykNcNkjcSi0GHtIpYjh6QX6P2uvR/S4+Bbb9p9rn ++hIy/ovu9tWN2hiPxGPe6torF6BulAxsTYlDercC204AyzsrdA0pr6HBgJH9C6ML1 ++TchwodbFJqn9rSv91i1liusAGoOvE81AGBdrXY7LxfSNhYY1IK6yR/POJPTd53sA ++uX2/j6Rtoksd/2BHPM6AUnI/2B9slhuzWX2aCtWLeuwvXDS6rYuTigaQmLkzTRfM ++dlMI3s9KLXxgi5YVumUZleJWXwBNP7KiKajd+VTSD+7WAhyhM5FIG5wVOaxmy4G2 ++TyqZ/Ax9d2VEjTQHWvQlLPQ4Mp0EIz0aEl94K/S8CK8bJRH6+PRkar+dJi1xqlL+ ++BYb42At9mEJ8odLlFikvNi1+t7jqXk5jRi5C0xFKx3nTtzoH2zNUeuA3R6vSocVK ++45jnze9IkKmxMlJ4loR5sgszdpDCD3kXqjtCcbMTmcrGyzJek3HSOTpiEORoTFOe ++Rhg6jH5lm+QcC263oipojS0qEQcnsWJP2CylNYMYHR9O/9NQxT3o2lsRHqZTMELV ++uQa/SFH+paQNbZOj8MRwPSqqiIxJFuLswKte1R+W7LKn1yBSM7Pp39lNbzGvJD2E ++YRfnCwFpJ54voVAuQ4jXJvigCW2qeCjXlxeD6K2j4eGJEEOmIjIW1wjubyBY6OI3 + -----END RSA PRIVATE KEY----- + -----BEGIN CERTIFICATE----- +-MIICVDCCAb2gAwIBAgIJANfHOBkZr8JOMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNV +-BAYTAlhZMRcwFQYDVQQHEw5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9u +-IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xMDEw +-MDgyMzAxNTZaFw0yMDEwMDUyMzAxNTZaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQH +-Ew5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9uIFNvZnR3YXJlIEZvdW5k +-YXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw +-gYkCgYEA21vT5isq7F68amYuuNpSFlKDPrMUCa4YWYqZRt2OZ+/3NKaZ2xAiSwr7 +-6MrQF70t5nLbSPpqE5+5VrS58SY+g/sXLiFd6AplH1wJZwh78DofbFYXUggktFMt +-pTyiX8jtP66bkcPkDADA089RI1TQR6Ca+n7HFa7c1fabVV6i3zkCAwEAAaMYMBYw +-FAYDVR0RBA0wC4IJbG9jYWxob3N0MA0GCSqGSIb3DQEBBQUAA4GBAHPctQBEQ4wd +-BJ6+JcpIraopLn8BGhbjNWj40mmRqWB/NAWF6M5ne7KpGAu7tLeG4hb1zLaldK8G +-lxy2GPSRF6LFS48dpEj2HbMv2nvv6xxalDMJ9+DicWgAKTQ6bcX2j3GUkCR0g/T1 +-CRlNBAAlvhKzO7Clpf9l0YKBEfraJByX ++MIIEWTCCAsGgAwIBAgIJAJinz4jHSjLtMA0GCSqGSIb3DQEBCwUAMF8xCzAJBgNV ++BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u ++IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xODA4 ++MjkxNDIzMTVaFw0yODA4MjYxNDIzMTVaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQH ++DA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9uIFNvZnR3YXJlIEZvdW5k ++YXRpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDCCAaIwDQYJKoZIhvcNAQEBBQADggGP ++ADCCAYoCggGBALKUqUtopT6E68kN+uJNEt34i2EbmG/bwjcD8IaMsgJPSsMO2Bpd ++3S6qWgkCeOyCfmAwBxK2kNbxGb63ouysEv7l8GCTJTWv3hG/HQcejJpnAEGi6K1U ++fDbyE/db6yZ12SoHVTGkadN4vYGCPd1Wj9ZO1F877SHQ8rDWX3xgTWkxN2ojBw44 ++T8RHSDiG8D/CvG4uEy+VUszL+Uvny5y2poNSqvI3J56sptWSrh8nIIbkPZPBdUne ++LYMOHTFK3ZjXSmhlXgziTxK71nnzM3Y9K9gxPnRqoXbvu/wFo55hQCkETiRkYgmm ++jXcBMZ0TClQVnQWuLjMthRnWFZs4Lfmwqjs7FZD/61581R2BYehvpWbLvvuOJhwv ++DFzexL2sXcAl7SsxbzeQKRHqGbIDfbnQTXfs3/VC6Ye5P82P2ucj+XC32N9piRmO ++gCBP8L3ub+YzzdxikZN2gZXXE2jsb3QyE/R2LkWdWyshpKe+RsZP1SBRbHShUyOh ++yJ90baoiEwj2mwIDAQABoxgwFjAUBgNVHREEDTALgglsb2NhbGhvc3QwDQYJKoZI ++hvcNAQELBQADggGBAHRUO/UIHl3jXQENewYayHxkIx8t7nu40iO2DXbicSijz5bo ++5//xAB6RxhBAlsDBehgQP1uoZg+WJW+nHu3CIVOU3qZNZRaozxiCl2UFKcNqLOmx ++R3NKpo1jYf4REQIeG8Yw9+hSWLRbshNteP6bKUUf+vanhg9+axyOEOH/iOQvgk/m ++b8wA8wNa4ujWljPbTQnj7ry8RqhTM0GcAN5LSdSvcKcpzLcs3aYwh+Z8e30sQWna ++F40sa5u7izgBTOrwpcDm/w5kC46vpRQ5fnbshVw6pne2by0mdMECASid/p25N103 ++jMqTFlmO7kpf/jpCSmamp3/JSEE1BJKHwQ6Ql4nzRA2N1mnvWH7Zxcv043gkHeAu ++0x8evpvwuhdIyproejNFlBpKmW8OX7yKTCPPMC/VkX8Q1rVkxU0DQ6hmvwZlhoKa ++9Wc2uXpw9xF8itV4Uvcdr3dwqByvIqn7iI/gB+4l41e0u8OmH2MKOx4Nxlly5TNW ++HcVKQHyOeyvnINuBAQ== + -----END CERTIFICATE----- +diff --git a/Lib/test/keycert.pem b/Lib/test/keycert.pem +index 64318aa2e0..0d39863373 100644 +--- a/Lib/test/keycert.pem ++++ b/Lib/test/keycert.pem +@@ -1,31 +1,66 @@ + -----BEGIN PRIVATE KEY----- +-MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANtb0+YrKuxevGpm +-LrjaUhZSgz6zFAmuGFmKmUbdjmfv9zSmmdsQIksK++jK0Be9LeZy20j6ahOfuVa0 +-ufEmPoP7Fy4hXegKZR9cCWcIe/A6H2xWF1IIJLRTLaU8ol/I7T+um5HD5AwAwNPP +-USNU0Eegmvp+xxWu3NX2m1Veot85AgMBAAECgYA3ZdZ673X0oexFlq7AAmrutkHt +-CL7LvwrpOiaBjhyTxTeSNWzvtQBkIU8DOI0bIazA4UreAFffwtvEuPmonDb3F+Iq +-SMAu42XcGyVZEl+gHlTPU9XRX7nTOXVt+MlRRRxL6t9GkGfUAXI3XxJDXW3c0vBK +-UL9xqD8cORXOfE06rQJBAP8mEX1ERkR64Ptsoe4281vjTlNfIbs7NMPkUnrn9N/Y +-BLhjNIfQ3HFZG8BTMLfX7kCS9D593DW5tV4Z9BP/c6cCQQDcFzCcVArNh2JSywOQ +-ZfTfRbJg/Z5Lt9Fkngv1meeGNPgIMLN8Sg679pAOOWmzdMO3V706rNPzSVMME7E5 +-oPIfAkEA8pDddarP5tCvTTgUpmTFbakm0KoTZm2+FzHcnA4jRh+XNTjTOv98Y6Ik +-eO5d1ZnKXseWvkZncQgxfdnMqqpj5wJAcNq/RVne1DbYlwWchT2Si65MYmmJ8t+F +-0mcsULqjOnEMwf5e+ptq5LzwbyrHZYq5FNk7ocufPv/ZQrcSSC+cFwJBAKvOJByS +-x56qyGeZLOQlWS2JS3KJo59XuLFGqcbgN9Om9xFa41Yb4N9NvplFivsvZdw3m1Q/ +-SPIXQuT8RMPDVNQ= ++MIIG/wIBADANBgkqhkiG9w0BAQEFAASCBukwggblAgEAAoIBgQCylKlLaKU+hOvJ ++DfriTRLd+IthG5hv28I3A/CGjLICT0rDDtgaXd0uqloJAnjsgn5gMAcStpDW8Rm+ ++t6LsrBL+5fBgkyU1r94Rvx0HHoyaZwBBouitVHw28hP3W+smddkqB1UxpGnTeL2B ++gj3dVo/WTtRfO+0h0PKw1l98YE1pMTdqIwcOOE/ER0g4hvA/wrxuLhMvlVLMy/lL ++58uctqaDUqryNyeerKbVkq4fJyCG5D2TwXVJ3i2DDh0xSt2Y10poZV4M4k8Su9Z5 ++8zN2PSvYMT50aqF277v8BaOeYUApBE4kZGIJpo13ATGdEwpUFZ0Fri4zLYUZ1hWb ++OC35sKo7OxWQ/+tefNUdgWHob6Vmy777jiYcLwxc3sS9rF3AJe0rMW83kCkR6hmy ++A3250E137N/1QumHuT/Nj9rnI/lwt9jfaYkZjoAgT/C97m/mM83cYpGTdoGV1xNo ++7G90MhP0di5FnVsrIaSnvkbGT9UgUWx0oVMjocifdG2qIhMI9psCAwEAAQKCAYBT ++sHmaPmNaZj59jZCqp0YVQlpHWwBYQ5vD3pPE6oCttm0p9nXt/VkfenQRTthOtmT1 ++POzDp00/feP7zeGLmqSYUjgRekPw4gdnN7Ip2PY5kdW77NWwDSzdLxuOS8Rq1MW9 ++/Yu+ZPe3RBlDbT8C0IM+Atlh/BqIQ3zIxN4g0pzUlF0M33d6AYfYSzOcUhibOO7H ++j84r+YXBNkIRgYKZYbutRXuZYaGuqejRpBj3voVu0d3Ntdb6lCWuClpB9HzfGN0c ++RTv8g6UYO4sK3qyFn90ibIR/1GB9watvtoWVZqggiWeBzSWVWRsGEf9O+Cx4oJw1 ++IphglhmhbgNksbj7bD24on/icldSOiVkoUemUOFmHWhCm4PnB1GmbD8YMfEdSbks ++qDr1Ps1zg4mGOinVD/4cY7vuPFO/HCH07wfeaUGzRt4g0/yLr+XjVofOA3oowyxv ++JAzr+niHA3lg5ecj4r7M68efwzN1OCyjMrVJw2RAzwvGxE+rm5NiT08SWlKQZnkC ++gcEA4wvyLpIur/UB84nV3XVJ89UMNBLm++aTFzld047BLJtMaOhvNqx6Cl5c8VuW ++l261KHjiVzpfNM3/A2LBQJcYkhX7avkqEXlj57cl+dCWAVwUzKmLJTPjfaTTZnYJ ++xeN3dMYjJz2z2WtgvfvDoJLukVwIMmhTY8wtqqYyQBJ/l06pBsfw5TNvmVIOQHds ++8ASOiFt+WRLk2bl9xrGGayqt3VV93KVRzF27cpjOgEcG74F3c0ZW9snERN7vIYwB ++JfrlAoHBAMlahPwMP2TYylG8OzHe7EiehTekSO26LGh0Cq3wTGXYsK/q8hQCzL14 ++kWW638vpwXL6L9ntvrd7hjzWRO3vX/VxnYEA6f0bpqHq1tZi6lzix5CTUN5McpDg ++QnjenSJNrNjS1zEF8WeY9iLEuDI/M/iUW4y9R6s3WpgQhPDXpSvd2g3gMGRUYhxQ ++Xna8auiJeYFq0oNaOxvJj+VeOfJ3ZMJttd+Y7gTOYZcbg3SdRb/kdxYki0RMD2hF ++4ZvjJ6CTfwKBwQDiMqiZFTJGQwYqp4vWEmAW+I4r4xkUpWatoI2Fk5eI5T9+1PLX ++uYXsho56NxEU1UrOg4Cb/p+TcBc8PErkGqR0BkpxDMOInTOXSrQe6lxIBoECVXc3 ++HTbrmiay0a5y5GfCgxPKqIJhfcToAceoVjovv0y7S4yoxGZKuUEe7E8JY2iqRNAO ++yOvKCCICv/hcN235E44RF+2/rDlOltagNej5tY6rIFkaDdgOF4bD7f9O5eEni1Bg ++litfoesDtQP/3rECgcEAkQfvQ7D6tIPmbqsbJBfCr6fmoqZllT4FIJN84b50+OL0 ++mTGsfjdqC4tdhx3sdu7/VPbaIqm5NmX10bowWgWSY7MbVME4yQPyqSwC5NbIonEC ++d6N0mzoLR0kQ+Ai4u+2g82gicgAq2oj1uSNi3WZi48jQjHYFulCbo246o1NgeFFK ++77WshYe2R1ioQfQDOU1URKCR0uTaMHClgfu112yiGd12JAD+aF3TM0kxDXz+sXI5 ++SKy311DFxECZeXRLpcC3AoHBAJkNMJWTyPYbeVu+CTQkec8Uun233EkXa2kUNZc/ ++5DuXDaK+A3DMgYRufTKSPpDHGaCZ1SYPInX1Uoe2dgVjWssRL2uitR4ENabDoAOA ++ICVYXYYNagqQu5wwirF0QeaMXo1fjhuuHQh8GsMdXZvYEaAITZ9/NG5x/oY08+8H ++kr78SMBOPy3XQn964uKG+e3JwpOG14GKABdAlrHKFXNWchu/6dgcYXB87mrC/GhO ++zNwzC+QhFTZoOomFoqMgFWujng== + -----END PRIVATE KEY----- + -----BEGIN CERTIFICATE----- +-MIICVDCCAb2gAwIBAgIJANfHOBkZr8JOMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNV +-BAYTAlhZMRcwFQYDVQQHEw5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9u +-IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xMDEw +-MDgyMzAxNTZaFw0yMDEwMDUyMzAxNTZaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQH +-Ew5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9uIFNvZnR3YXJlIEZvdW5k +-YXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw +-gYkCgYEA21vT5isq7F68amYuuNpSFlKDPrMUCa4YWYqZRt2OZ+/3NKaZ2xAiSwr7 +-6MrQF70t5nLbSPpqE5+5VrS58SY+g/sXLiFd6AplH1wJZwh78DofbFYXUggktFMt +-pTyiX8jtP66bkcPkDADA089RI1TQR6Ca+n7HFa7c1fabVV6i3zkCAwEAAaMYMBYw +-FAYDVR0RBA0wC4IJbG9jYWxob3N0MA0GCSqGSIb3DQEBBQUAA4GBAHPctQBEQ4wd +-BJ6+JcpIraopLn8BGhbjNWj40mmRqWB/NAWF6M5ne7KpGAu7tLeG4hb1zLaldK8G +-lxy2GPSRF6LFS48dpEj2HbMv2nvv6xxalDMJ9+DicWgAKTQ6bcX2j3GUkCR0g/T1 +-CRlNBAAlvhKzO7Clpf9l0YKBEfraJByX ++MIIEWTCCAsGgAwIBAgIJAJinz4jHSjLtMA0GCSqGSIb3DQEBCwUAMF8xCzAJBgNV ++BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u ++IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xODA4 ++MjkxNDIzMTVaFw0yODA4MjYxNDIzMTVaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQH ++DA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9uIFNvZnR3YXJlIEZvdW5k ++YXRpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDCCAaIwDQYJKoZIhvcNAQEBBQADggGP ++ADCCAYoCggGBALKUqUtopT6E68kN+uJNEt34i2EbmG/bwjcD8IaMsgJPSsMO2Bpd ++3S6qWgkCeOyCfmAwBxK2kNbxGb63ouysEv7l8GCTJTWv3hG/HQcejJpnAEGi6K1U ++fDbyE/db6yZ12SoHVTGkadN4vYGCPd1Wj9ZO1F877SHQ8rDWX3xgTWkxN2ojBw44 ++T8RHSDiG8D/CvG4uEy+VUszL+Uvny5y2poNSqvI3J56sptWSrh8nIIbkPZPBdUne ++LYMOHTFK3ZjXSmhlXgziTxK71nnzM3Y9K9gxPnRqoXbvu/wFo55hQCkETiRkYgmm ++jXcBMZ0TClQVnQWuLjMthRnWFZs4Lfmwqjs7FZD/61581R2BYehvpWbLvvuOJhwv ++DFzexL2sXcAl7SsxbzeQKRHqGbIDfbnQTXfs3/VC6Ye5P82P2ucj+XC32N9piRmO ++gCBP8L3ub+YzzdxikZN2gZXXE2jsb3QyE/R2LkWdWyshpKe+RsZP1SBRbHShUyOh ++yJ90baoiEwj2mwIDAQABoxgwFjAUBgNVHREEDTALgglsb2NhbGhvc3QwDQYJKoZI ++hvcNAQELBQADggGBAHRUO/UIHl3jXQENewYayHxkIx8t7nu40iO2DXbicSijz5bo ++5//xAB6RxhBAlsDBehgQP1uoZg+WJW+nHu3CIVOU3qZNZRaozxiCl2UFKcNqLOmx ++R3NKpo1jYf4REQIeG8Yw9+hSWLRbshNteP6bKUUf+vanhg9+axyOEOH/iOQvgk/m ++b8wA8wNa4ujWljPbTQnj7ry8RqhTM0GcAN5LSdSvcKcpzLcs3aYwh+Z8e30sQWna ++F40sa5u7izgBTOrwpcDm/w5kC46vpRQ5fnbshVw6pne2by0mdMECASid/p25N103 ++jMqTFlmO7kpf/jpCSmamp3/JSEE1BJKHwQ6Ql4nzRA2N1mnvWH7Zxcv043gkHeAu ++0x8evpvwuhdIyproejNFlBpKmW8OX7yKTCPPMC/VkX8Q1rVkxU0DQ6hmvwZlhoKa ++9Wc2uXpw9xF8itV4Uvcdr3dwqByvIqn7iI/gB+4l41e0u8OmH2MKOx4Nxlly5TNW ++HcVKQHyOeyvnINuBAQ== + -----END CERTIFICATE----- +diff --git a/Lib/test/keycert2.pem b/Lib/test/keycert2.pem +index c4a18bf2cf..ed6ae85a46 100644 +--- a/Lib/test/keycert2.pem ++++ b/Lib/test/keycert2.pem +@@ -1,31 +1,66 @@ + -----BEGIN PRIVATE KEY----- +-MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBANcLaMB7T/Wi9DBc +-PltGzgt8cxsv55m7PQPHMZvn6Ke8xmNqcmEzib8opRwKGrCV6TltKeFlNSg8dwQK +-Tl4ktyTkGCVweRQJ37AkBayvEBml5s+QD4vlhqkJPsL/Nsd+fnqngOGc5+59+C6r +-s3XpiLlF5ah/z8q92Mnw54nypw1JAgMBAAECgYBE3t2Mj7GbDLZB6rj5yKJioVfI +-BD6bSJEQ7bGgqdQkLFwpKMU7BiN+ekjuwvmrRkesYZ7BFgXBPiQrwhU5J28Tpj5B +-EOMYSIOHfzdalhxDGM1q2oK9LDFiCotTaSdEzMYadel5rmKXJ0zcK2Jho0PCuECf +-tf/ghRxK+h1Hm0tKgQJBAO6MdGDSmGKYX6/5kPDje7we/lSLorSDkYmV0tmVShsc +-JxgaGaapazceA/sHL3Myx7Eenkip+yPYDXEDFvAKNDECQQDmxsT9NOp6mo7ISvky +-GFr2vVHsJ745BMWoma4rFjPBVnS8RkgK+b2EpDCdZSrQ9zw2r8sKTgrEyrDiGTEg +-wJyZAkA8OOc0flYMJg2aHnYR6kwVjPmGHI5h5gk648EMPx0rROs1sXkiUwkHLCOz +-HvhCq+Iv+9vX2lnVjbiu/CmxRdIxAkA1YEfzoKeTD+hyXxTgB04Sv5sRGegfXAEz +-i8gC4zG5R/vcCA1lrHmvEiLEZL/QcT6WD3bQvVg0SAU9ZkI8pxARAkA7yqMSvP1l +-gJXy44R+rzpLYb1/PtiLkIkaKG3x9TUfPnfD2jY09fPkZlfsRU3/uS09IkhSwimV +-d5rWoljEfdou ++MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQDKjrjWZlfOs1Ch ++qt1RoyLfqyXbHVXIAW0fTzAxfJnxvFOiWqAAKgC2qVQM8Y080kRUuRaXP/w9ywXT +++MzX6tByy5VbTYJYyTjHOH46EWLNdcqEJs4+FCVqOIYrQPQ6pGAhCXmgBy4Vb42J ++ABLwb+Kt+y2Dk15tggVcAHP2Khri+lRXWvda+kZAe2F1IojmuWyCTy3FEYHic5qN ++BsXcf6u1oyFV8MybOuz1zGj3vd2C+dEKO4Ohw9rRwnvHSatjM+CfwiXf8kTXzDBF ++Z/8W3+6yA49pHxRbG7FE3K1TAPhkrp+BVTIUOcdI74wEA6UEkWFF5sQcmmAth59M ++EQrl2CXorftEPhsKZE59dUP1+nYAPvR/mTySNCSw7/rvdf+csRSZ5ollMu/lxsht ++ulJYJI03+IiDTn47FI5D+IF25REK7d4LzGIo6T73ktsT+qpSXHuTWC+IABm8AMF9 ++7ljxHSwMRU/z+O5uiONRItDAgKH/OItFG54PtY2vAhaO0YiZrZcCAwEAAQKCAYB2 ++hTo8IVghlySH5B1p5kXCkDcvVaPaypLaLhCp9Blzq9lX9yUF043lU4Ddrf0RaIsY ++88/3IjZqxb+cP0lE0Z20fdDfwqORZfQ2BaU+PuwMAm9EEhy9kDYwR/ChoHkHUyT4 ++T7392BWr70Dmt8ddLmp5mK4R/gnTk6+lHJK9p/dhdk4haxWvAyBWHJty2Yk3T6nh ++OYkzdUIFidUVza+6jG2hc1lPGv3tmnYKgNeulkblm10oWphz79C6ycx5WG7TNgef ++CQ3z7//Nn89YTiaUBjLvoLvxRTMwO96r7E/FaslSl/fWnF3HP3lut26Z/mNfhiwj ++qn7AhUwpSNPV0qcxFWXr/rXUjdk745wv8wOODK8atjjE/vt/MRBK0rAOIPSm3ecx ++37PKNtR4i+sNeDEcY1IyTHE6wFvJSy5y8AFpn5y8tbqYfhlEVWZ4pcnlrKxhWm7j ++oBkB/4GBjKQgbQ7ttym9eNG1wIbZ8v9N06+yeLs/NCc4bFZEgcWjFqBH1bLtAYEC ++gcEA8tt8iYNqbsDH2ognjEmbbBxrDBmyYcEKRpg1i1SUopcZl8i93IHpG7EgJIaj ++l7aWSbASAxjnK02t0VZ3nNS60acibzRwY/+e8OrSqlQdMXlAB2ggBA86drDJpfBl ++WGJG8TJVY9bc1TU2uuwtZR1LAMSsRHVp+3IvKLpHrne5exPd3x6KGYcuaM+Uk/rE ++u6tLsFNwaCdh+iBFFDT2bnYIw7jAsokJUkwxMVxSC0/21s2blhO/q5LsN1gFC1kN ++TbpXAoHBANWE7TmG2szPvujPwrK18v6iJlHCA2n50AgAQXrsetj2JcF3HYHYdHnq ++z36MQ6FpBKOiQumozWvb32WTjEwdG2kix7GEfam4DAUBdqYuCHzPcR12K5Tc8hsX ++NG7JXUAeS8ZJEiOdu95X59JHyBxUQtNfte5rcbaV17SVw6K6bsWVJnj60YjtJrpa ++xHvv1ZRnT2WEzJGpA+ii1h3I52N7ipGBiw172qcW+bKJukMi8eHxx5CC9e5tBpnu ++C+Ou/eYewQKBwHxNa0jXQrq9YY2w8s0TP8HuKbxfyrXOIHxRm9ZczFcMD8VosgUT ++WUUbO+B2KXWVtwawYAfFz0ySzcy//SkAmT6F1VIl/QCx7aBSENGti+Ous98WpIxv ++XvUxN4T/rl+2raj2ok4fw5g9TG4QRIvkmmciQyonDr/sicbG0bmy/fTJDl8NOpIm ++ZtKurNWxHNERtAPkMTyeK7/ilHjrQtb3AzVqcvbuvR6qcONa5YN0wlrfkisWoJwo ++707EdpCAXBbUsQKBwQCnpzcpu2Sj+t9ZKIElF87T93gFLETH+ppJHgJMRdDz+NqO ++fTwTD2XtsNz57aLQ44f8AFVv6NZbQYq41FEOFrDGLcQE9BZDpDrz10FVnMGXVr7n ++tjjkK1SCxwapkr0AsoknCYsPojO4kud46loLPHI4TGeq7HyeNCvqJMo3RRHjXIiX ++58GNNUD6hHjRI/FdFH14Jf0GxmJGUU20l2Jwb7nPJJuNm9mE53pqoNA7FP4+Pj1H ++kD0Q2FSdmxeE0IuWHEECgcBgw6ogJ/FRRGLcym+aApqP9BChK+W8FDfDc9Mi4p/J ++g+XmetWNFGCGTlOefGqUDIkwSG+QVOEN3hxziXbsjnvfpGApqoaulAI5oRvrwIcj ++QIvD2mt0PB52k5ZL9QL2K9sgBa43BJDyCKooMAlTy2XMM+NyXVxQKmzf3r3jQ5sl ++Rptk7ro38a9G8Rs99RFDyOmP1haOM0KXZvPksN4nsXuTlE01cnwnI29XKAlEZaoA ++pQPLXD8W/KK4mwDbmokYXmo= + -----END PRIVATE KEY----- + -----BEGIN CERTIFICATE----- +-MIICXTCCAcagAwIBAgIJALVQzebTtrXFMA0GCSqGSIb3DQEBBQUAMGIxCzAJBgNV ++MIIEYjCCAsqgAwIBAgIJAJm2YulYpr+6MA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV + BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u + IFNvZnR3YXJlIEZvdW5kYXRpb24xFTATBgNVBAMMDGZha2Vob3N0bmFtZTAeFw0x +-NDExMjMxNzAwMDdaFw0yNDExMjAxNzAwMDdaMGIxCzAJBgNVBAYTAlhZMRcwFQYD ++ODA4MjkxNDIzMTZaFw0yODA4MjYxNDIzMTZaMGIxCzAJBgNVBAYTAlhZMRcwFQYD + VQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9uIFNvZnR3YXJlIEZv +-dW5kYXRpb24xFTATBgNVBAMMDGZha2Vob3N0bmFtZTCBnzANBgkqhkiG9w0BAQEF +-AAOBjQAwgYkCgYEA1wtowHtP9aL0MFw+W0bOC3xzGy/nmbs9A8cxm+fop7zGY2py +-YTOJvyilHAoasJXpOW0p4WU1KDx3BApOXiS3JOQYJXB5FAnfsCQFrK8QGaXmz5AP +-i+WGqQk+wv82x35+eqeA4Zzn7n34LquzdemIuUXlqH/Pyr3YyfDnifKnDUkCAwEA +-AaMbMBkwFwYDVR0RBBAwDoIMZmFrZWhvc3RuYW1lMA0GCSqGSIb3DQEBBQUAA4GB +-AKuay3vDKfWzt5+ch/HHBsert84ISot4fUjzXDA/oOgTOEjVcSShHxqNShMOW1oA +-QYBpBB/5Kx5RkD/w6imhucxt2WQPRgjX4x4bwMipVH/HvFDp03mG51/Cpi1TyZ74 +-El7qa/Pd4lHhOLzMKBA6503fpeYSFUIBxZbGLqylqRK7 ++dW5kYXRpb24xFTATBgNVBAMMDGZha2Vob3N0bmFtZTCCAaIwDQYJKoZIhvcNAQEB ++BQADggGPADCCAYoCggGBAMqOuNZmV86zUKGq3VGjIt+rJdsdVcgBbR9PMDF8mfG8 ++U6JaoAAqALapVAzxjTzSRFS5Fpc//D3LBdP4zNfq0HLLlVtNgljJOMc4fjoRYs11 ++yoQmzj4UJWo4hitA9DqkYCEJeaAHLhVvjYkAEvBv4q37LYOTXm2CBVwAc/YqGuL6 ++VFda91r6RkB7YXUiiOa5bIJPLcURgeJzmo0Gxdx/q7WjIVXwzJs67PXMaPe93YL5 ++0Qo7g6HD2tHCe8dJq2Mz4J/CJd/yRNfMMEVn/xbf7rIDj2kfFFsbsUTcrVMA+GSu ++n4FVMhQ5x0jvjAQDpQSRYUXmxByaYC2Hn0wRCuXYJeit+0Q+GwpkTn11Q/X6dgA+ ++9H+ZPJI0JLDv+u91/5yxFJnmiWUy7+XGyG26UlgkjTf4iINOfjsUjkP4gXblEQrt ++3gvMYijpPveS2xP6qlJce5NYL4gAGbwAwX3uWPEdLAxFT/P47m6I41Ei0MCAof84 ++i0Ubng+1ja8CFo7RiJmtlwIDAQABoxswGTAXBgNVHREEEDAOggxmYWtlaG9zdG5h ++bWUwDQYJKoZIhvcNAQELBQADggGBAMIVLp6e6saH2NQSg8iFg8Ewg/K/etI++jHo ++gCJ697AY02wtfrBox1XtljlmI2xpJtVAYZWHhrNqwrEG43aB7YEV6RqTcG6QUVqa ++NbD8iNCnMKm7fP89hZizmqA1l4aHnieI3ucOqpgooM7FQwLX6qk+rSue6lD5N/5f ++avsublnj8rNKyDfHpQ3AWduLoj8QqctpzI3CqoDZNLNzaDnzVWpxT1SKDQ88q7VI ++W5zb+lndpdQlCu3v5HM4w5UpwL/k1htl/z6PnPseS2UdlXv6A8KITnCLg5PLP4tz ++2oTAg9gjOtRP/0uwkhvicwoFzFJNVT813lzTLE1jlobMPiZhsS1mjaJGPD9GQZDK ++ny3j8ogrIRGjnI4xpOMNNDVphcvwtV8fRbvURSHCj9Y4kCLpD5ODuoyEyLYicJIv ++GZP456GP0iSCK5GKO0ij/YzGCkPWD5zA+mYFpMMGZPTwajenMw7TVaPXcc9CZBtr ++oOjwwiLEqdkpxUj13mJYTlt5wsS/Kw== + -----END CERTIFICATE----- +diff --git a/Lib/test/keycert3.pem b/Lib/test/keycert3.pem +index 5bfa62c4ca..e0a8205a66 100644 +--- a/Lib/test/keycert3.pem ++++ b/Lib/test/keycert3.pem +@@ -1,73 +1,164 @@ + -----BEGIN PRIVATE KEY----- +-MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMLgD0kAKDb5cFyP +-jbwNfR5CtewdXC+kMXAWD8DLxiTTvhMW7qVnlwOm36mZlszHKvsRf05lT4pegiFM +-9z2j1OlaN+ci/X7NU22TNN6crYSiN77FjYJP464j876ndSxyD+rzys386T+1r1aZ +-aggEdkj1TsSsv1zWIYKlPIjlvhuxAgMBAAECgYA0aH+T2Vf3WOPv8KdkcJg6gCRe +-yJKXOWgWRcicx/CUzOEsTxmFIDPLxqAWA3k7v0B+3vjGw5Y9lycV/5XqXNoQI14j +-y09iNsumds13u5AKkGdTJnZhQ7UKdoVHfuP44ZdOv/rJ5/VD6F4zWywpe90pcbK+ +-AWDVtusgGQBSieEl1QJBAOyVrUG5l2yoUBtd2zr/kiGm/DYyXlIthQO/A3/LngDW +-5/ydGxVsT7lAVOgCsoT+0L4efTh90PjzW8LPQrPBWVMCQQDS3h/FtYYd5lfz+FNL +-9CEe1F1w9l8P749uNUD0g317zv1tatIqVCsQWHfVHNdVvfQ+vSFw38OORO00Xqs9 +-1GJrAkBkoXXEkxCZoy4PteheO/8IWWLGGr6L7di6MzFl1lIqwT6D8L9oaV2vynFT +-DnKop0pa09Unhjyw57KMNmSE2SUJAkEArloTEzpgRmCq4IK2/NpCeGdHS5uqRlbh +-1VIa/xGps7EWQl5Mn8swQDel/YP3WGHTjfx7pgSegQfkyaRtGpZ9OQJAa9Vumj8m +-JAAtI0Bnga8hgQx7BhTQY4CadDxyiRGOGYhwUzYVCqkb2sbVRH9HnwUaJT7cWBY3 +-RnJdHOMXWem7/w== ++MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQCfKC83Qe9/ZGMW ++YhbpARRiKco6mJI9CNNeaf7A89TE+w5Y3GSwS8uzqp5C6QebZzPNueg8HYoTwN85 ++Z3xM036/Qw9KhQVth+XDAqM+19e5KHkYcxg3d3ZI1HgY170eakaLBvMDN5ULoFOw ++Is2PtwM2o9cjd5mfSuWttI6+fCqop8/l8cerG9iX2GH39p3iWwWoTZuYndAA9qYv ++07YWajuQ1ESWKPjHYGTnMvu4xIzibC1mXd2M6u/IjNO6g426SKFaRDWQkx01gIV/ ++CyKs9DgZoeMHkKZuPqZVOxOK+A/NrmrqHFsPIsrs5wk7QAVju5/X1skpn/UGQlmM ++RwBaQULOs1FagA+54RXU6qUPW0YmhJ4xOB4gHHD1vjAKEsRZ7/6zcxMyOm+M1DbK ++RTH4NWjVWpnY8XaVGdRhtTpH9MjycpKhF+D2Zdy2tQXtqu2GdcMnUedt13fn9xDu ++P4PophE0ip/IMgn+kb4m9e+S+K9lldQl0B+4BcGWAqHelh2KuU0CAwEAAQKCAYEA ++lKiWIYjmyRjdLKUGPTES9vWNvNmRjozV0RQ0LcoSbMMLDZkeO0UwyWqOVHUQ8+ib ++jIcfEjeNJxI57oZopeHOO5vJhpNlFH+g7ltiW2qERqA1K88lSXm99Bzw6FNqhCRE ++K8ub5N9fyfJA+P4o/xm0WK8EXk5yIUV17p/9zJJxzgKgv2jsVTi3QG2OZGvn4Oug ++ByomMZEGHkBDzdxz8c/cP1Tlk1RFuwSgews178k2xq7AYSM/s0YmHi7b/RSvptX6 ++1v8P8kXNUe4AwTaNyrlvF2lwIadZ8h1hA7tCE2n44b7a7KfhAkwcbr1T59ioYh6P ++zxsyPT678uD51dbtD/DXJCcoeeFOb8uzkR2KNcrnQzZpCJnRq4Gp5ybxwsxxuzpr ++gz0gbNlhuWtE7EoSzmIK9t+WTS7IM2CvZymd6/OAh1Fuw6AQhSp64XRp3OfMMAAC ++Ie2EPtKj4islWGT8VoUjuRYGmdRh4duAH1dkiAXOWA3R7y5a1/y/iE8KE8BtxocB ++AoHBAM8aiURgpu1Fs0Oqz6izec7KSLL3l8hmW+MKUOfk/Ybng6FrTFsL5YtzR+Ap ++wW4wwWnnIKEc1JLiZ7g8agRETK8hr5PwFXUn/GSWC0SMsazLJToySQS5LOV0tLzK ++kJ3jtNU7tnlDGNkCHTHSoVL2T/8t+IkZI/h5Z6wjlYPvU2Iu0nVIXtiG+alv4A6M ++Hrh9l5or4mjB6rGnVXeYohLkCm6s/W97ahVxLMcEdbsBo1prm2JqGnSoiR/tEFC/ ++QHQnbQKBwQDEu7kW0Yg9sZ89QtYtVQ1YpixFZORaUeRIRLnpEs1w7L1mCbOZ2Lj9 ++JHxsH05cYAc7HJfPwwxv3+3aGAIC/dfu4VSwEFtatAzUpzlhzKS5+HQCWB4JUNNU ++MQ3+FwK2xQX4Ph8t+OzrFiYcK2g0An5UxWMa2HWIAWUOhnTOydAVsoH6yP31cVm4 ++0hxoABCwflaNLNGjRUyfBpLTAcNu/YtcE+KREy7YAAgXXrhRSO4XpLsSXwLnLT7/ ++YOkoBWDcTWECgcBPWnSUDZCIQ3efithMZJBciqd2Y2X19Dpq8O31HImD4jtOY0V7 ++cUB/wSkeHAGwjd/eCyA2e0x8B2IEdqmMfvr+86JJxekC3dJYXCFvH5WIhsH53YCa ++3bT1KlWCLP9ib/g+58VQC0R/Cc9T4sfLePNH7D5ZkZd1wlbV30CPr+i8KwKay6MD ++xhvtLx+jk07GE+E9wmjbCMo7TclyrLoVEOlqZMAqshgApT+p9eyCPetwXuDHwa3n ++WxhHclcZCV7R4rUCgcAkdGSnxcvpIrDPOUNWwxvmAWTStw9ZbTNP8OxCNCm9cyDl ++d4bAS1h8D/a+Uk7C70hnu7Sl2w7C7Eu2zhwRUdhhe3+l4GINPK/j99i6NqGPlGpq ++xMlMEJ4YS768BqeKFpg0l85PRoEgTsphDeoROSUPsEPdBZ9BxIBlYKTkbKESZDGR ++twzYHljx1n1NCDYPflmrb1KpXn4EOcObNghw2KqqNUUWfOeBPwBA1FxzM4BrAStp ++DBINpGS4Dc0mjViVegECgcA3hTtm82XdxQXj9LQmb/E3lKx/7H87XIOeNMmvjYuZ ++iS9wKrkF+u42vyoDxcKMCnxP5056wpdST4p56r+SBwVTHcc3lGBSGcMTIfwRXrj3 ++thOA2our2n4ouNIsYyTlcsQSzifwmpRmVMRPxl9fYVdEWUgB83FgHT0D9avvZnF9 ++t9OccnGJXShAIZIBADhVj/JwG4FbaX42NijD5PNpVLk1Y17OV0I576T9SfaQoBjJ ++aH1M/zC4aVaS0DYB/Gxq7v8= + -----END PRIVATE KEY----- + Certificate: + Data: +- Version: 1 (0x0) +- Serial Number: 12723342612721443281 (0xb09264b1f2da21d1) +- Signature Algorithm: sha1WithRSAEncryption ++ Version: 3 (0x2) ++ Serial Number: ++ cb:2d:80:99:5a:69:52:5c ++ Signature Algorithm: sha256WithRSAEncryption + Issuer: C=XY, O=Python Software Foundation CA, CN=our-ca-server + Validity +- Not Before: Jan 4 19:47:07 2013 GMT +- Not After : Nov 13 19:47:07 2022 GMT ++ Not Before: Aug 29 14:23:16 2018 GMT ++ Not After : Jul 7 14:23:16 2028 GMT + Subject: C=XY, L=Castle Anthrax, O=Python Software Foundation, CN=localhost + Subject Public Key Info: + Public Key Algorithm: rsaEncryption +- Public-Key: (1024 bit) ++ Public-Key: (3072 bit) + Modulus: +- 00:c2:e0:0f:49:00:28:36:f9:70:5c:8f:8d:bc:0d: +- 7d:1e:42:b5:ec:1d:5c:2f:a4:31:70:16:0f:c0:cb: +- c6:24:d3:be:13:16:ee:a5:67:97:03:a6:df:a9:99: +- 96:cc:c7:2a:fb:11:7f:4e:65:4f:8a:5e:82:21:4c: +- f7:3d:a3:d4:e9:5a:37:e7:22:fd:7e:cd:53:6d:93: +- 34:de:9c:ad:84:a2:37:be:c5:8d:82:4f:e3:ae:23: +- f3:be:a7:75:2c:72:0f:ea:f3:ca:cd:fc:e9:3f:b5: +- af:56:99:6a:08:04:76:48:f5:4e:c4:ac:bf:5c:d6: +- 21:82:a5:3c:88:e5:be:1b:b1 ++ 00:9f:28:2f:37:41:ef:7f:64:63:16:62:16:e9:01: ++ 14:62:29:ca:3a:98:92:3d:08:d3:5e:69:fe:c0:f3: ++ d4:c4:fb:0e:58:dc:64:b0:4b:cb:b3:aa:9e:42:e9: ++ 07:9b:67:33:cd:b9:e8:3c:1d:8a:13:c0:df:39:67: ++ 7c:4c:d3:7e:bf:43:0f:4a:85:05:6d:87:e5:c3:02: ++ a3:3e:d7:d7:b9:28:79:18:73:18:37:77:76:48:d4: ++ 78:18:d7:bd:1e:6a:46:8b:06:f3:03:37:95:0b:a0: ++ 53:b0:22:cd:8f:b7:03:36:a3:d7:23:77:99:9f:4a: ++ e5:ad:b4:8e:be:7c:2a:a8:a7:cf:e5:f1:c7:ab:1b: ++ d8:97:d8:61:f7:f6:9d:e2:5b:05:a8:4d:9b:98:9d: ++ d0:00:f6:a6:2f:d3:b6:16:6a:3b:90:d4:44:96:28: ++ f8:c7:60:64:e7:32:fb:b8:c4:8c:e2:6c:2d:66:5d: ++ dd:8c:ea:ef:c8:8c:d3:ba:83:8d:ba:48:a1:5a:44: ++ 35:90:93:1d:35:80:85:7f:0b:22:ac:f4:38:19:a1: ++ e3:07:90:a6:6e:3e:a6:55:3b:13:8a:f8:0f:cd:ae: ++ 6a:ea:1c:5b:0f:22:ca:ec:e7:09:3b:40:05:63:bb: ++ 9f:d7:d6:c9:29:9f:f5:06:42:59:8c:47:00:5a:41: ++ 42:ce:b3:51:5a:80:0f:b9:e1:15:d4:ea:a5:0f:5b: ++ 46:26:84:9e:31:38:1e:20:1c:70:f5:be:30:0a:12: ++ c4:59:ef:fe:b3:73:13:32:3a:6f:8c:d4:36:ca:45: ++ 31:f8:35:68:d5:5a:99:d8:f1:76:95:19:d4:61:b5: ++ 3a:47:f4:c8:f2:72:92:a1:17:e0:f6:65:dc:b6:b5: ++ 05:ed:aa:ed:86:75:c3:27:51:e7:6d:d7:77:e7:f7: ++ 10:ee:3f:83:e8:a6:11:34:8a:9f:c8:32:09:fe:91: ++ be:26:f5:ef:92:f8:af:65:95:d4:25:d0:1f:b8:05: ++ c1:96:02:a1:de:96:1d:8a:b9:4d + Exponent: 65537 (0x10001) +- Signature Algorithm: sha1WithRSAEncryption +- 2f:42:5f:a3:09:2c:fa:51:88:c7:37:7f:ea:0e:63:f0:a2:9a: +- e5:5a:e2:c8:20:f0:3f:60:bc:c8:0f:b6:c6:76:ce:db:83:93: +- f5:a3:33:67:01:8e:04:cd:00:9a:73:fd:f3:35:86:fa:d7:13: +- e2:46:c6:9d:c0:29:53:d4:a9:90:b8:77:4b:e6:83:76:e4:92: +- d6:9c:50:cf:43:d0:c6:01:77:61:9a:de:9b:70:f7:72:cd:59: +- 00:31:69:d9:b4:ca:06:9c:6d:c3:c7:80:8c:68:e6:b5:a2:f8: +- ef:1d:bb:16:9f:77:77:ef:87:62:22:9b:4d:69:a4:3a:1a:f1: +- 21:5e:8c:32:ac:92:fd:15:6b:18:c2:7f:15:0d:98:30:ca:75: +- 8f:1a:71:df:da:1d:b2:ef:9a:e8:2d:2e:02:fd:4a:3c:aa:96: +- 0b:06:5d:35:b3:3d:24:87:4b:e0:b0:58:60:2f:45:ac:2e:48: +- 8a:b0:99:10:65:27:ff:cc:b1:d8:fd:bd:26:6b:b9:0c:05:2a: +- f4:45:63:35:51:07:ed:83:85:fe:6f:69:cb:bb:40:a8:ae:b6: +- 3b:56:4a:2d:a4:ed:6d:11:2c:4d:ed:17:24:fd:47:bc:d3:41: +- a2:d3:06:fe:0c:90:d8:d8:94:26:c4:ff:cc:a1:d8:42:77:eb: +- fc:a9:94:71 ++ X509v3 extensions: ++ X509v3 Subject Alternative Name: ++ DNS:localhost ++ X509v3 Key Usage: critical ++ Digital Signature, Key Encipherment ++ X509v3 Extended Key Usage: ++ TLS Web Server Authentication, TLS Web Client Authentication ++ X509v3 Basic Constraints: critical ++ CA:FALSE ++ X509v3 Subject Key Identifier: ++ 8F:EA:1D:E3:33:5C:00:16:B3:8B:6F:6B:6F:D3:4C:CB:B5:CB:7C:55 ++ X509v3 Authority Key Identifier: ++ keyid:DD:BF:CA:DA:E6:D1:34:BA:37:75:21:CA:6F:9A:08:28:F2:35:B6:48 ++ DirName:/C=XY/O=Python Software Foundation CA/CN=our-ca-server ++ serial:CB:2D:80:99:5A:69:52:5B ++ ++ Authority Information Access: ++ CA Issuers - URI:http://testca.pythontest.net/testca/pycacert.cer ++ OCSP - URI:http://testca.pythontest.net/testca/ocsp/ ++ ++ X509v3 CRL Distribution Points: ++ ++ Full Name: ++ URI:http://testca.pythontest.net/testca/revocation.crl ++ ++ Signature Algorithm: sha256WithRSAEncryption ++ 27:f5:8c:59:10:f4:c6:e7:28:00:bf:ba:8d:7b:13:03:f1:1c: ++ a6:5f:b3:06:55:a4:22:b9:db:b2:d5:46:bd:f7:0c:dd:43:6e: ++ b4:79:65:67:21:0c:2a:55:ee:40:8e:85:9f:9f:47:bb:0a:2a: ++ 4d:b6:64:74:98:a0:7f:ae:dc:f1:2e:db:42:77:18:e0:75:8b: ++ 26:35:68:c3:41:ed:6b:c8:77:72:6f:6a:9a:5d:55:69:02:fd: ++ 5a:54:c8:57:cb:b0:65:03:16:e2:0f:00:39:99:66:a0:9b:88: ++ 93:17:e2:5a:2d:79:35:5f:97:57:78:c4:af:f5:99:5e:86:ab: ++ d3:11:ad:1a:a2:0d:fa:52:10:b9:fe:bf:9d:ce:33:d9:86:b2: ++ 9c:16:f8:d6:75:08:8a:db:0a:e5:b4:2b:16:7f:b4:f9:2a:9f: ++ c3:d2:77:d7:cd:65:1e:f4:6c:1e:eb:59:b9:f0:ae:5f:a4:1f: ++ cc:4a:c4:b9:7a:a9:d9:6b:32:68:3b:e1:65:b0:84:b7:90:c4: ++ ae:fe:f4:37:4f:21:a0:de:9f:3a:b1:e5:cc:16:04:66:3f:0b: ++ 41:dc:42:3d:20:3e:ec:b7:95:2b:35:57:fa:be:7f:b6:3a:ba: ++ ca:4f:58:fe:75:3e:08:89:2c:8c:b0:5d:2e:f9:89:10:2b:f9: ++ 41:46:4f:3c:00:b7:27:d3:65:24:28:17:23:26:31:42:ea:7e: ++ 4e:93:e4:7b:68:54:ca:9f:46:f3:ef:2b:e9:85:0c:b5:84:b2: ++ d5:35:34:80:75:2b:f0:91:23:b8:08:01:8e:b9:0a:54:d4:fb: ++ 34:52:fe:d9:45:f0:80:3b:b6:c1:6f:82:d1:1f:f2:3b:08:f6: ++ 46:a6:96:27:61:4b:58:32:7a:0e:1d:59:c5:44:ad:5e:1a:79: ++ 33:c1:d4:05:2f:4a:d3:d8:42:42:8d:33:e3:63:ca:d5:87:97: ++ 9b:4d:b8:1a:03:34:bb:1c:d2:02:3f:59:23:e2:23:80:88:63: ++ c2:f0:a2:63:a8:8b + -----BEGIN CERTIFICATE----- +-MIICpDCCAYwCCQCwkmSx8toh0TANBgkqhkiG9w0BAQUFADBNMQswCQYDVQQGEwJY +-WTEmMCQGA1UECgwdUHl0aG9uIFNvZnR3YXJlIEZvdW5kYXRpb24gQ0ExFjAUBgNV +-BAMMDW91ci1jYS1zZXJ2ZXIwHhcNMTMwMTA0MTk0NzA3WhcNMjIxMTEzMTk0NzA3 +-WjBfMQswCQYDVQQGEwJYWTEXMBUGA1UEBxMOQ2FzdGxlIEFudGhyYXgxIzAhBgNV +-BAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMRIwEAYDVQQDEwlsb2NhbGhv +-c3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMLgD0kAKDb5cFyPjbwNfR5C +-tewdXC+kMXAWD8DLxiTTvhMW7qVnlwOm36mZlszHKvsRf05lT4pegiFM9z2j1Ola +-N+ci/X7NU22TNN6crYSiN77FjYJP464j876ndSxyD+rzys386T+1r1aZaggEdkj1 +-TsSsv1zWIYKlPIjlvhuxAgMBAAEwDQYJKoZIhvcNAQEFBQADggEBAC9CX6MJLPpR +-iMc3f+oOY/CimuVa4sgg8D9gvMgPtsZ2ztuDk/WjM2cBjgTNAJpz/fM1hvrXE+JG +-xp3AKVPUqZC4d0vmg3bkktacUM9D0MYBd2Ga3ptw93LNWQAxadm0ygacbcPHgIxo +-5rWi+O8duxafd3fvh2Iim01ppDoa8SFejDKskv0VaxjCfxUNmDDKdY8acd/aHbLv +-mugtLgL9SjyqlgsGXTWzPSSHS+CwWGAvRawuSIqwmRBlJ//Msdj9vSZruQwFKvRF +-YzVRB+2Dhf5vacu7QKiutjtWSi2k7W0RLE3tFyT9R7zTQaLTBv4MkNjYlCbE/8yh +-2EJ36/yplHE= ++MIIF8TCCBFmgAwIBAgIJAMstgJlaaVJcMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNV ++BAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUgRm91bmRhdGlvbiBDQTEW ++MBQGA1UEAwwNb3VyLWNhLXNlcnZlcjAeFw0xODA4MjkxNDIzMTZaFw0yODA3MDcx ++NDIzMTZaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEj ++MCEGA1UECgwaUHl0aG9uIFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMMCWxv ++Y2FsaG9zdDCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBAJ8oLzdB739k ++YxZiFukBFGIpyjqYkj0I015p/sDz1MT7DljcZLBLy7OqnkLpB5tnM8256DwdihPA ++3zlnfEzTfr9DD0qFBW2H5cMCoz7X17koeRhzGDd3dkjUeBjXvR5qRosG8wM3lQug ++U7AizY+3Azaj1yN3mZ9K5a20jr58Kqinz+Xxx6sb2JfYYff2neJbBahNm5id0AD2 ++pi/TthZqO5DURJYo+MdgZOcy+7jEjOJsLWZd3Yzq78iM07qDjbpIoVpENZCTHTWA ++hX8LIqz0OBmh4weQpm4+plU7E4r4D82uauocWw8iyuznCTtABWO7n9fWySmf9QZC ++WYxHAFpBQs6zUVqAD7nhFdTqpQ9bRiaEnjE4HiAccPW+MAoSxFnv/rNzEzI6b4zU ++NspFMfg1aNVamdjxdpUZ1GG1Okf0yPJykqEX4PZl3La1Be2q7YZ1wydR523Xd+f3 ++EO4/g+imETSKn8gyCf6Rvib175L4r2WV1CXQH7gFwZYCod6WHYq5TQIDAQABo4IB ++wDCCAbwwFAYDVR0RBA0wC4IJbG9jYWxob3N0MA4GA1UdDwEB/wQEAwIFoDAdBgNV ++HSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4E ++FgQUj+od4zNcABazi29rb9NMy7XLfFUwfQYDVR0jBHYwdIAU3b/K2ubRNLo3dSHK ++b5oIKPI1tkihUaRPME0xCzAJBgNVBAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29m ++dHdhcmUgRm91bmRhdGlvbiBDQTEWMBQGA1UEAwwNb3VyLWNhLXNlcnZlcoIJAMst ++gJlaaVJbMIGDBggrBgEFBQcBAQR3MHUwPAYIKwYBBQUHMAKGMGh0dHA6Ly90ZXN0 ++Y2EucHl0aG9udGVzdC5uZXQvdGVzdGNhL3B5Y2FjZXJ0LmNlcjA1BggrBgEFBQcw ++AYYpaHR0cDovL3Rlc3RjYS5weXRob250ZXN0Lm5ldC90ZXN0Y2Evb2NzcC8wQwYD ++VR0fBDwwOjA4oDagNIYyaHR0cDovL3Rlc3RjYS5weXRob250ZXN0Lm5ldC90ZXN0 ++Y2EvcmV2b2NhdGlvbi5jcmwwDQYJKoZIhvcNAQELBQADggGBACf1jFkQ9MbnKAC/ ++uo17EwPxHKZfswZVpCK527LVRr33DN1DbrR5ZWchDCpV7kCOhZ+fR7sKKk22ZHSY ++oH+u3PEu20J3GOB1iyY1aMNB7WvId3JvappdVWkC/VpUyFfLsGUDFuIPADmZZqCb ++iJMX4loteTVfl1d4xK/1mV6Gq9MRrRqiDfpSELn+v53OM9mGspwW+NZ1CIrbCuW0 ++KxZ/tPkqn8PSd9fNZR70bB7rWbnwrl+kH8xKxLl6qdlrMmg74WWwhLeQxK7+9DdP ++IaDenzqx5cwWBGY/C0HcQj0gPuy3lSs1V/q+f7Y6uspPWP51PgiJLIywXS75iRAr +++UFGTzwAtyfTZSQoFyMmMULqfk6T5HtoVMqfRvPvK+mFDLWEstU1NIB1K/CRI7gI ++AY65ClTU+zRS/tlF8IA7tsFvgtEf8jsI9kamlidhS1gyeg4dWcVErV4aeTPB1AUv ++StPYQkKNM+NjytWHl5tNuBoDNLsc0gI/WSPiI4CIY8LwomOoiw== + -----END CERTIFICATE----- +diff --git a/Lib/test/keycert4.pem b/Lib/test/keycert4.pem +index 53355c8a50..d1ebb82486 100644 +--- a/Lib/test/keycert4.pem ++++ b/Lib/test/keycert4.pem +@@ -1,73 +1,164 @@ + -----BEGIN PRIVATE KEY----- +-MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAK5UQiMI5VkNs2Qv +-L7gUaiDdFevNUXRjU4DHAe3ZzzYLZNE69h9gO9VCSS16tJ5fT5VEu0EZyGr0e3V2 +-NkX0ZoU0Hc/UaY4qx7LHmn5SYZpIxhJnkf7SyHJK1zUaGlU0/LxYqIuGCtF5dqx1 +-L2OQhEx1GM6RydHdgX69G64LXcY5AgMBAAECgYAhsRMfJkb9ERLMl/oG/5sLQu9L +-pWDKt6+ZwdxzlZbggQ85CMYshjLKIod2DLL/sLf2x1PRXyRG131M1E3k8zkkz6de +-R1uDrIN/x91iuYzfLQZGh8bMY7Yjd2eoroa6R/7DjpElGejLxOAaDWO0ST2IFQy9 +-myTGS2jSM97wcXfsSQJBANP3jelJoS5X6BRjTSneY21wcocxVuQh8pXpErALVNsT +-drrFTeaBuZp7KvbtnIM5g2WRNvaxLZlAY/hXPJvi6ncCQQDSix1cebml6EmPlEZS +-Mm8gwI2F9ufUunwJmBJcz826Do0ZNGByWDAM/JQZH4FX4GfAFNuj8PUb+GQfadkx +-i1DPAkEA0lVsNHojvuDsIo8HGuzarNZQT2beWjJ1jdxh9t7HrTx7LIps6rb/fhOK +-Zs0R6gVAJaEbcWAPZ2tFyECInAdnsQJAUjaeXXjuxFkjOFym5PvqpvhpivEx78Bu +-JPTr3rAKXmfGMxxfuOa0xK1wSyshP6ZR/RBn/+lcXPKubhHQDOegwwJAJF1DBQnN +-+/tLmOPULtDwfP4Zixn+/8GmGOahFoRcu6VIGHmRilJTn6MOButw7Glv2YdeC6l/ +-e83Gq6ffLVfKNQ== ++MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQDGjpiHzq7ghxhM ++ZzrnRsGBC/cmw8EREIdbqlrz/l8BFaWeipvO5Hb/MyU8xs2zLUrqIr2JNf+Eii8Y ++m4bYmZclFra4jomaiSlxTZOe3dMV8m4vAq4eT2mSfZZC1+XAutqdz7WhHxhMVEm3 ++AyTWvTC3qCbnlbX5VIoQUwFrsSWqDiHyaGdK3rrOTKFUKM8YPiq/BZkm6A4eiFci ++5wd/SPD+w0pIscZbQW1MUr5bs54uylWaUmtfI8KJt6BDZQ/uA06c6i863sSCEI6L ++gq+wyikeJGNMxZMfgu3dzfv4BiZBQX0ZhiRvqseDSdPcuVa2Ifb6CFlg298neweY ++4EAIE1O+uqo5h8FF1aUOMZpQEZuzsp9R/TAMBHX1YmVjG/kRdBeaHe3whzB1Pfue ++PIX2ZTMmLNYbYbfnmxhk1nn8aAvoT98pNw8y3/2k2KNsu24n9uSkkxAoqJ19WKwm ++mL8MpJKAzLv45tRvhN+QLtnRdu+LJ9m29npQHFmYLbdqRfmidnMCAwEAAQKCAYBd ++w1C8MRnb5W/QBJ+IP515NxFLOP2e9VM2MkgpGGH8vSAssf/Jv5GCCcD35lmU1zqd ++PjKK7PjwueBrmmYfOshpN0Sp+oV4eHUdkCi5yL65inYFtRpMLewIxU2D2zgfvx0l ++kMSQhYKP6O22gsGOtmCfGcTlb4kzaHyaINh25nyGxY26TxsX+/3zFbTJbUv+grzk ++39vmx4aDXJbpYHfl36gOZmJZ2bl1tnvKovhJjZSRO/MYoPsbPmPLbO89ZCgVmXFc ++GVkb5Cram6i3iyutSDjxWN7Fb8uy8pFLPGAXZgF7pQoXPSEHZe8GEWBnWSC9KaDa ++uM9Ir847/Muy1ceCmxKcI2WrSjoH2AhPcmHgvbPE9Mynr6+uzReSP3q7Wh9PHm23 ++oFx3DwdCfmjysnpAMBawNmJdWyxVDbZ6eyrhp17ADpsMaDTynZ+fJjgMr+MmWtbU ++YSRD0wWtl/DrzsaePZsOjCpKYJyulC+rh9/Zz1aiwrGWPbgEAzDrD6Q1Zp0mUCEC ++gcEA+XskmGIB9rRPy+YQmRgzQ555PsjLWsnQsNktP6KBhlQjFKJZXRZ0DxDTS7h8 ++NrJrUDBmwfsgzggVbeO55VP5FGwD6DNeO/Bz++Fdevh8uKQFHDfk4sbIUPS91qw4 ++s7OW7PR7C7Jf7Dnjmsn42o2lO4FsbcEn2F+PHOvoLl/OrSx73lS/RkdOEItW8d8/ ++ExRohylnba/I2vCE9bNZd4DGjMW87j/THKPadDZWEqWggcrjY8x6ibSQGm2n2Tka ++8B+vAoHBAMu+zl8kqFlYDG24dGfVpMaOYj5Osj0cV5f7O2pZ15sCevjiqoKGHH7G ++O8EiI5pRBZ893+Fsx6YWmcKue88lfGvaoQjV0LUbfMfX/FoD39w/ZLx31yKEiFuc ++KvMiRV5mO3kQiHBVX9vamzr5NeaErccXY9LnhaKOMX9blgiDQZH7fc3RhodcFWrC ++9yfX6ryfidpPnRvK7Ops7hVnFKyyS4FaAarnzH1B2WcVcD4lYYxhMc8VXeU3eKOh ++j1fI/F5ifQKBwQDpCjB670HqUzAexL9IYqSwSz3yedoK6m24ZIWx5XicI8fJJIXZ ++QHoVAKB/IMtWxH8dnri+Bnj0O/TYe1pQb4pBm0xjAGjMEKYm6LNLhQXr67qiS0vQ ++0eKYTKVv+9vTcLRQj2bI3Exh+wkys+tzK9DmrtS8CSvRICIs3+g4OWJzvRPP8NXj ++LgQrzBzhPqpKhkvFxdVJTmSOrxFj+a5exLmzEZqT6qanIB+VYpQwQuqVkxGpTX5B ++V5ssNLYPYRpapx0CgcByCtQixzcAA1u5knR9pkT76ris3YnA0Ptqk3I3XiBjoGjK ++pL0CICUVBMpvmTdKai12a8DDwgqiOaZJJTchxH63NAHNGzkeFkuq5IdYrzB/bHBr ++WbzukjZs6KXVv4oKg7ioVAu6rN7iBaO7x8BWzk8i0EHMzFCto1+rRM1e6HEsUBOj ++v7LIU0+dmZGUGLRIbhhQPR3Yb6ZatSwyiKc23vmKZqHmUqbQOaqBm6te7beDRugF ++XJVY9sqs9IJyhYpVHlUCgcAPoslwYKeAXagsxdQrH3D9VJDXVOHWKMBqQZDio5dB ++Q80uWpuxtt6nhZkQO1JIWnYb6v+zbDbcgjByBIDuxCdBW9d+QQnanKmVyrXguK91 ++C3OcHHOmSduFdWC3/zYW1mW97Tz1sXyam2hly1u3L5kW+GnE1hr9VVPjQNrO9+Ge ++qW0coaJqKY78q3Rm2dtyZeJSFFI1o/DQ3blyItsFpg/QrR+a5XrS6Nw2ZLIL4Azo ++J1CTgMwjhwlMNCI4t4dkHd0= + -----END PRIVATE KEY----- + Certificate: + Data: +- Version: 1 (0x0) +- Serial Number: 12723342612721443282 (0xb09264b1f2da21d2) +- Signature Algorithm: sha1WithRSAEncryption ++ Version: 3 (0x2) ++ Serial Number: ++ cb:2d:80:99:5a:69:52:5d ++ Signature Algorithm: sha256WithRSAEncryption + Issuer: C=XY, O=Python Software Foundation CA, CN=our-ca-server + Validity +- Not Before: Jan 4 19:47:07 2013 GMT +- Not After : Nov 13 19:47:07 2022 GMT ++ Not Before: Aug 29 14:23:16 2018 GMT ++ Not After : Jul 7 14:23:16 2028 GMT + Subject: C=XY, L=Castle Anthrax, O=Python Software Foundation, CN=fakehostname + Subject Public Key Info: + Public Key Algorithm: rsaEncryption +- Public-Key: (1024 bit) ++ Public-Key: (3072 bit) + Modulus: +- 00:ae:54:42:23:08:e5:59:0d:b3:64:2f:2f:b8:14: +- 6a:20:dd:15:eb:cd:51:74:63:53:80:c7:01:ed:d9: +- cf:36:0b:64:d1:3a:f6:1f:60:3b:d5:42:49:2d:7a: +- b4:9e:5f:4f:95:44:bb:41:19:c8:6a:f4:7b:75:76: +- 36:45:f4:66:85:34:1d:cf:d4:69:8e:2a:c7:b2:c7: +- 9a:7e:52:61:9a:48:c6:12:67:91:fe:d2:c8:72:4a: +- d7:35:1a:1a:55:34:fc:bc:58:a8:8b:86:0a:d1:79: +- 76:ac:75:2f:63:90:84:4c:75:18:ce:91:c9:d1:dd: +- 81:7e:bd:1b:ae:0b:5d:c6:39 ++ 00:c6:8e:98:87:ce:ae:e0:87:18:4c:67:3a:e7:46: ++ c1:81:0b:f7:26:c3:c1:11:10:87:5b:aa:5a:f3:fe: ++ 5f:01:15:a5:9e:8a:9b:ce:e4:76:ff:33:25:3c:c6: ++ cd:b3:2d:4a:ea:22:bd:89:35:ff:84:8a:2f:18:9b: ++ 86:d8:99:97:25:16:b6:b8:8e:89:9a:89:29:71:4d: ++ 93:9e:dd:d3:15:f2:6e:2f:02:ae:1e:4f:69:92:7d: ++ 96:42:d7:e5:c0:ba:da:9d:cf:b5:a1:1f:18:4c:54: ++ 49:b7:03:24:d6:bd:30:b7:a8:26:e7:95:b5:f9:54: ++ 8a:10:53:01:6b:b1:25:aa:0e:21:f2:68:67:4a:de: ++ ba:ce:4c:a1:54:28:cf:18:3e:2a:bf:05:99:26:e8: ++ 0e:1e:88:57:22:e7:07:7f:48:f0:fe:c3:4a:48:b1: ++ c6:5b:41:6d:4c:52:be:5b:b3:9e:2e:ca:55:9a:52: ++ 6b:5f:23:c2:89:b7:a0:43:65:0f:ee:03:4e:9c:ea: ++ 2f:3a:de:c4:82:10:8e:8b:82:af:b0:ca:29:1e:24: ++ 63:4c:c5:93:1f:82:ed:dd:cd:fb:f8:06:26:41:41: ++ 7d:19:86:24:6f:aa:c7:83:49:d3:dc:b9:56:b6:21: ++ f6:fa:08:59:60:db:df:27:7b:07:98:e0:40:08:13: ++ 53:be:ba:aa:39:87:c1:45:d5:a5:0e:31:9a:50:11: ++ 9b:b3:b2:9f:51:fd:30:0c:04:75:f5:62:65:63:1b: ++ f9:11:74:17:9a:1d:ed:f0:87:30:75:3d:fb:9e:3c: ++ 85:f6:65:33:26:2c:d6:1b:61:b7:e7:9b:18:64:d6: ++ 79:fc:68:0b:e8:4f:df:29:37:0f:32:df:fd:a4:d8: ++ a3:6c:bb:6e:27:f6:e4:a4:93:10:28:a8:9d:7d:58: ++ ac:26:98:bf:0c:a4:92:80:cc:bb:f8:e6:d4:6f:84: ++ df:90:2e:d9:d1:76:ef:8b:27:d9:b6:f6:7a:50:1c: ++ 59:98:2d:b7:6a:45:f9:a2:76:73 + Exponent: 65537 (0x10001) +- Signature Algorithm: sha1WithRSAEncryption +- ad:45:8a:8e:ef:c6:ef:04:41:5c:2c:4a:84:dc:02:76:0c:d0: +- 66:0f:f0:16:04:58:4d:fd:68:b7:b8:d3:a8:41:a5:5c:3c:6f: +- 65:3c:d1:f8:ce:43:35:e7:41:5f:53:3d:c9:2c:c3:7d:fc:56: +- 4a:fa:47:77:38:9d:bb:97:28:0a:3b:91:19:7f:bc:74:ae:15: +- 6b:bd:20:36:67:45:a5:1e:79:d7:75:e6:89:5c:6d:54:84:d1: +- 95:d7:a7:b4:33:3c:af:37:c4:79:8f:5e:75:dc:75:c2:18:fb: +- 61:6f:2d:dc:38:65:5b:ba:67:28:d0:88:d7:8d:b9:23:5a:8e: +- e8:c6:bb:db:ce:d5:b8:41:2a:ce:93:08:b6:95:ad:34:20:18: +- d5:3b:37:52:74:50:0b:07:2c:b0:6d:a4:4c:7b:f4:e0:fd:d1: +- af:17:aa:20:cd:62:e3:f0:9d:37:69:db:41:bd:d4:1c:fb:53: +- 20:da:88:9d:76:26:67:ce:01:90:a7:80:1d:a9:5b:39:73:68: +- 54:0a:d1:2a:03:1b:8f:3c:43:5d:5d:c4:51:f1:a7:e7:11:da: +- 31:2c:49:06:af:04:f4:b8:3c:99:c4:20:b9:06:36:a2:00:92: +- 61:1d:0c:6d:24:05:e2:82:e1:47:db:a0:5f:ba:b9:fb:ba:fa: +- 49:12:1e:ce ++ X509v3 extensions: ++ X509v3 Subject Alternative Name: ++ DNS:fakehostname ++ X509v3 Key Usage: critical ++ Digital Signature, Key Encipherment ++ X509v3 Extended Key Usage: ++ TLS Web Server Authentication, TLS Web Client Authentication ++ X509v3 Basic Constraints: critical ++ CA:FALSE ++ X509v3 Subject Key Identifier: ++ 52:E0:93:AA:52:55:B7:BB:E7:A8:E0:8C:DE:41:2E:F4:07:F0:36:FB ++ X509v3 Authority Key Identifier: ++ keyid:DD:BF:CA:DA:E6:D1:34:BA:37:75:21:CA:6F:9A:08:28:F2:35:B6:48 ++ DirName:/C=XY/O=Python Software Foundation CA/CN=our-ca-server ++ serial:CB:2D:80:99:5A:69:52:5B ++ ++ Authority Information Access: ++ CA Issuers - URI:http://testca.pythontest.net/testca/pycacert.cer ++ OCSP - URI:http://testca.pythontest.net/testca/ocsp/ ++ ++ X509v3 CRL Distribution Points: ++ ++ Full Name: ++ URI:http://testca.pythontest.net/testca/revocation.crl ++ ++ Signature Algorithm: sha256WithRSAEncryption ++ 29:d2:3f:82:3f:c1:38:35:a6:bd:81:10:fe:64:ec:ff:7e:e1: ++ c6:6f:7f:86:65:f9:31:6f:fb:ef:32:4e:2f:87:c8:42:de:6c: ++ 8d:b8:06:08:8f:37:70:95:7d:e1:40:d4:82:2b:8d:b3:4a:fd: ++ 34:c5:9e:df:ff:01:53:4a:4f:08:f4:58:e1:74:fc:78:e3:3e: ++ 71:a7:5e:66:07:ea:d2:04:31:e2:75:a8:4c:80:17:86:92:20: ++ d2:32:a7:9a:65:8b:1a:5f:f1:4c:c8:50:6d:00:fc:99:bf:69: ++ b3:48:f3:45:5a:ee:35:50:14:b8:f3:92:92:c6:9f:0e:5d:eb: ++ 0d:e8:ec:f2:a4:09:6b:dc:66:2b:fc:df:4c:fc:65:a1:ae:d3: ++ b5:88:6a:a4:e7:08:1c:94:49:e0:b8:c1:04:8c:21:09:6c:55: ++ 4b:2c:97:10:f1:8c:6c:d0:bb:ba:8d:93:e8:47:8b:4d:8e:7d: ++ 7d:85:53:18:c8:f8:f4:8f:67:3a:b1:aa:3e:18:34:6c:3a:e6: ++ a6:c7:2f:be:83:38:f5:d5:e5:d2:17:28:61:6c:b6:49:99:21: ++ 69:a4:a8:b6:94:76:fd:18:ad:35:52:45:64:fb:f1:5d:8e:bb: ++ c0:21:2e:59:55:24:af:bb:8f:b2:0a:7b:17:f0:34:97:8e:68: ++ a9:f2:d0:3e:f6:73:82:f8:7c:4e:9a:70:7d:d6:b3:8c:cc:85: ++ 04:5c:02:8f:74:da:88:3a:20:a8:7e:c2:9e:b0:dd:56:1f:ce: ++ cd:42:16:c6:14:91:ad:30:e0:dc:76:f2:2c:56:ea:38:45:d8: ++ c0:3e:b8:90:fa:f3:38:99:ec:44:07:35:8f:69:62:0c:f9:ef: ++ b7:9d:e5:15:42:6e:fb:fe:4c:ff:e8:94:5a:1a:b0:80:b2:0e: ++ 17:3d:e1:87:a8:08:84:93:74:68:8d:29:df:ca:0b:6a:44:32: ++ 8a:51:3b:d6:38:db:bd:e3:2a:1b:5e:20:48:81:82:19:91:c6: ++ 87:8c:0f:cd:51:ea + -----BEGIN CERTIFICATE----- +-MIICpzCCAY8CCQCwkmSx8toh0jANBgkqhkiG9w0BAQUFADBNMQswCQYDVQQGEwJY +-WTEmMCQGA1UECgwdUHl0aG9uIFNvZnR3YXJlIEZvdW5kYXRpb24gQ0ExFjAUBgNV +-BAMMDW91ci1jYS1zZXJ2ZXIwHhcNMTMwMTA0MTk0NzA3WhcNMjIxMTEzMTk0NzA3 +-WjBiMQswCQYDVQQGEwJYWTEXMBUGA1UEBxMOQ2FzdGxlIEFudGhyYXgxIzAhBgNV +-BAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMRUwEwYDVQQDEwxmYWtlaG9z +-dG5hbWUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAK5UQiMI5VkNs2QvL7gU +-aiDdFevNUXRjU4DHAe3ZzzYLZNE69h9gO9VCSS16tJ5fT5VEu0EZyGr0e3V2NkX0 +-ZoU0Hc/UaY4qx7LHmn5SYZpIxhJnkf7SyHJK1zUaGlU0/LxYqIuGCtF5dqx1L2OQ +-hEx1GM6RydHdgX69G64LXcY5AgMBAAEwDQYJKoZIhvcNAQEFBQADggEBAK1Fio7v +-xu8EQVwsSoTcAnYM0GYP8BYEWE39aLe406hBpVw8b2U80fjOQzXnQV9TPcksw338 +-Vkr6R3c4nbuXKAo7kRl/vHSuFWu9IDZnRaUeedd15olcbVSE0ZXXp7QzPK83xHmP +-XnXcdcIY+2FvLdw4ZVu6ZyjQiNeNuSNajujGu9vO1bhBKs6TCLaVrTQgGNU7N1J0 +-UAsHLLBtpEx79OD90a8XqiDNYuPwnTdp20G91Bz7UyDaiJ12JmfOAZCngB2pWzlz +-aFQK0SoDG488Q11dxFHxp+cR2jEsSQavBPS4PJnEILkGNqIAkmEdDG0kBeKC4Ufb +-oF+6ufu6+kkSHs4= ++MIIF9zCCBF+gAwIBAgIJAMstgJlaaVJdMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNV ++BAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUgRm91bmRhdGlvbiBDQTEW ++MBQGA1UEAwwNb3VyLWNhLXNlcnZlcjAeFw0xODA4MjkxNDIzMTZaFw0yODA3MDcx ++NDIzMTZaMGIxCzAJBgNVBAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEj ++MCEGA1UECgwaUHl0aG9uIFNvZnR3YXJlIEZvdW5kYXRpb24xFTATBgNVBAMMDGZh ++a2Vob3N0bmFtZTCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBAMaOmIfO ++ruCHGExnOudGwYEL9ybDwREQh1uqWvP+XwEVpZ6Km87kdv8zJTzGzbMtSuoivYk1 ++/4SKLxibhtiZlyUWtriOiZqJKXFNk57d0xXybi8Crh5PaZJ9lkLX5cC62p3PtaEf ++GExUSbcDJNa9MLeoJueVtflUihBTAWuxJaoOIfJoZ0reus5MoVQozxg+Kr8FmSbo ++Dh6IVyLnB39I8P7DSkixxltBbUxSvluzni7KVZpSa18jwom3oENlD+4DTpzqLzre ++xIIQjouCr7DKKR4kY0zFkx+C7d3N+/gGJkFBfRmGJG+qx4NJ09y5VrYh9voIWWDb ++3yd7B5jgQAgTU766qjmHwUXVpQ4xmlARm7Oyn1H9MAwEdfViZWMb+RF0F5od7fCH ++MHU9+548hfZlMyYs1htht+ebGGTWefxoC+hP3yk3DzLf/aTYo2y7bif25KSTECio ++nX1YrCaYvwykkoDMu/jm1G+E35Au2dF274sn2bb2elAcWZgtt2pF+aJ2cwIDAQAB ++o4IBwzCCAb8wFwYDVR0RBBAwDoIMZmFrZWhvc3RuYW1lMA4GA1UdDwEB/wQEAwIF ++oDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAd ++BgNVHQ4EFgQUUuCTqlJVt7vnqOCM3kEu9AfwNvswfQYDVR0jBHYwdIAU3b/K2ubR ++NLo3dSHKb5oIKPI1tkihUaRPME0xCzAJBgNVBAYTAlhZMSYwJAYDVQQKDB1QeXRo ++b24gU29mdHdhcmUgRm91bmRhdGlvbiBDQTEWMBQGA1UEAwwNb3VyLWNhLXNlcnZl ++coIJAMstgJlaaVJbMIGDBggrBgEFBQcBAQR3MHUwPAYIKwYBBQUHMAKGMGh0dHA6 ++Ly90ZXN0Y2EucHl0aG9udGVzdC5uZXQvdGVzdGNhL3B5Y2FjZXJ0LmNlcjA1Bggr ++BgEFBQcwAYYpaHR0cDovL3Rlc3RjYS5weXRob250ZXN0Lm5ldC90ZXN0Y2Evb2Nz ++cC8wQwYDVR0fBDwwOjA4oDagNIYyaHR0cDovL3Rlc3RjYS5weXRob250ZXN0Lm5l ++dC90ZXN0Y2EvcmV2b2NhdGlvbi5jcmwwDQYJKoZIhvcNAQELBQADggGBACnSP4I/ ++wTg1pr2BEP5k7P9+4cZvf4Zl+TFv++8yTi+HyELebI24BgiPN3CVfeFA1IIrjbNK ++/TTFnt//AVNKTwj0WOF0/HjjPnGnXmYH6tIEMeJ1qEyAF4aSINIyp5plixpf8UzI ++UG0A/Jm/abNI80Va7jVQFLjzkpLGnw5d6w3o7PKkCWvcZiv830z8ZaGu07WIaqTn ++CByUSeC4wQSMIQlsVUsslxDxjGzQu7qNk+hHi02OfX2FUxjI+PSPZzqxqj4YNGw6 ++5qbHL76DOPXV5dIXKGFstkmZIWmkqLaUdv0YrTVSRWT78V2Ou8AhLllVJK+7j7IK ++exfwNJeOaKny0D72c4L4fE6acH3Ws4zMhQRcAo902og6IKh+wp6w3VYfzs1CFsYU ++ka0w4Nx28ixW6jhF2MA+uJD68ziZ7EQHNY9pYgz577ed5RVCbvv+TP/olFoasICy ++Dhc94YeoCISTdGiNKd/KC2pEMopRO9Y4273jKhteIEiBghmRxoeMD81R6g== + -----END CERTIFICATE----- +diff --git a/Lib/test/make_ssl_certs.py b/Lib/test/make_ssl_certs.py +index a1f298de34..ca2c12cada 100644 +--- a/Lib/test/make_ssl_certs.py ++++ b/Lib/test/make_ssl_certs.py +@@ -50,7 +50,7 @@ req_template = """ + dir = cadir + database = $dir/index.txt + crlnumber = $dir/crl.txt +- default_md = sha1 ++ default_md = sha256 + default_days = 3600 + default_crl_days = 3600 + certificate = pycacert.pem +@@ -88,7 +88,9 @@ req_template = """ + + here = os.path.abspath(os.path.dirname(__file__)) + +-def make_cert_key(hostname, sign=False, extra_san=''): ++ ++def make_cert_key(hostname, sign=False, extra_san='', ++ ext='req_x509_extensions_full', key='rsa:3072'): + print("creating cert for " + hostname) + tempnames = [] + for i in range(3): +@@ -146,7 +148,7 @@ def make_ca(): + t.flush() + with tempfile.NamedTemporaryFile() as f: + args = ['req', '-new', '-days', '3650', '-extensions', 'v3_ca', '-nodes', +- '-newkey', 'rsa:2048', '-keyout', 'pycakey.pem', ++ '-newkey', 'rsa:3072', '-keyout', 'pycakey.pem', + '-out', f.name, + '-subj', '/C=XY/L=Castle Anthrax/O=Python Software Foundation CA/CN=our-ca-server'] + check_call(['openssl'] + args) +diff --git a/Lib/test/pycacert.pem b/Lib/test/pycacert.pem +index 09b1f3e08a..73150c960f 100644 +--- a/Lib/test/pycacert.pem ++++ b/Lib/test/pycacert.pem +@@ -1,78 +1,99 @@ + Certificate: + Data: + Version: 3 (0x2) +- Serial Number: 12723342612721443280 (0xb09264b1f2da21d0) +- Signature Algorithm: sha1WithRSAEncryption ++ Serial Number: ++ cb:2d:80:99:5a:69:52:5b ++ Signature Algorithm: sha256WithRSAEncryption + Issuer: C=XY, O=Python Software Foundation CA, CN=our-ca-server + Validity +- Not Before: Jan 4 19:47:07 2013 GMT +- Not After : Jan 2 19:47:07 2023 GMT ++ Not Before: Aug 29 14:23:16 2018 GMT ++ Not After : Aug 26 14:23:16 2028 GMT + Subject: C=XY, O=Python Software Foundation CA, CN=our-ca-server + Subject Public Key Info: + Public Key Algorithm: rsaEncryption +- Public-Key: (2048 bit) ++ Public-Key: (3072 bit) + Modulus: +- 00:e7:de:e9:e3:0c:9f:00:b6:a1:fd:2b:5b:96:d2: +- 6f:cc:e0:be:86:b9:20:5e:ec:03:7a:55:ab:ea:a4: +- e9:f9:49:85:d2:66:d5:ed:c7:7a:ea:56:8e:2d:8f: +- e7:42:e2:62:28:a9:9f:d6:1b:8e:eb:b5:b4:9c:9f: +- 14:ab:df:e6:94:8b:76:1d:3e:6d:24:61:ed:0c:bf: +- 00:8a:61:0c:df:5c:c8:36:73:16:00:cd:47:ba:6d: +- a4:a4:74:88:83:23:0a:19:fc:09:a7:3c:4a:4b:d3: +- e7:1d:2d:e4:ea:4c:54:21:f3:26:db:89:37:18:d4: +- 02:bb:40:32:5f:a4:ff:2d:1c:f7:d4:bb:ec:8e:cf: +- 5c:82:ac:e6:7c:08:6c:48:85:61:07:7f:25:e0:5c: +- e0:bc:34:5f:e0:b9:04:47:75:c8:47:0b:8d:bc:d6: +- c8:68:5f:33:83:62:d2:20:44:35:b1:ad:81:1a:8a: +- cd:bc:35:b0:5c:8b:47:d6:18:e9:9c:18:97:cc:01: +- 3c:29:cc:e8:1e:e4:e4:c1:b8:de:e7:c2:11:18:87: +- 5a:93:34:d8:a6:25:f7:14:71:eb:e4:21:a2:d2:0f: +- 2e:2e:d4:62:00:35:d3:d6:ef:5c:60:4b:4c:a9:14: +- e2:dd:15:58:46:37:33:26:b7:e7:2e:5d:ed:42:e4: +- c5:4d ++ 00:97:ed:55:41:ba:36:17:95:db:71:1c:d3:e1:61: ++ ac:58:73:e3:c6:96:cf:2b:1f:b8:08:f5:9d:4b:4b: ++ c7:30:f6:b8:0b:b3:52:72:a0:bb:c9:4d:3b:8e:df: ++ 22:8e:01:57:81:c9:92:73:cc:00:c6:ec:70:b0:3a: ++ 17:40:c1:df:f2:8c:36:4c:c4:a7:81:e7:b6:24:68: ++ e2:a0:7e:35:07:2f:a0:5b:f9:45:46:f7:1e:f0:46: ++ 11:fe:ca:1a:3c:50:f1:26:a9:5f:9c:22:9c:f8:41: ++ e1:df:4f:12:95:19:2f:5c:90:01:17:6e:7e:3e:7d: ++ cf:e9:09:af:25:f8:f8:42:77:2d:6d:5f:36:f2:78: ++ 1e:7d:4a:87:68:63:6c:06:71:1b:8d:fa:25:fe:d4: ++ d3:f5:a5:17:b1:ef:ea:17:cb:54:c8:27:99:80:cb: ++ 3c:45:f1:2c:52:1c:dd:1f:51:45:20:50:1e:5e:ab: ++ 57:73:1b:41:78:96:de:84:a4:7a:dd:8f:30:85:36: ++ 58:79:76:a0:d2:61:c8:1b:a9:94:99:63:c6:ee:f8: ++ 14:bf:b4:52:56:31:97:fa:eb:ac:53:9e:95:ce:4c: ++ c4:5a:4a:b7:ca:03:27:5b:35:57:ce:02:dc:ec:ca: ++ 69:f8:8a:5a:39:cb:16:20:15:03:24:61:6c:f4:7a: ++ fc:b6:48:e5:59:10:5c:49:d0:23:9f:fb:71:5e:3a: ++ e9:68:9f:34:72:80:27:b6:3f:4c:b1:d9:db:63:7f: ++ 67:68:4a:6e:11:f8:e8:c0:f4:5a:16:39:53:0b:68: ++ de:77:fa:45:e7:f8:91:cd:78:cd:28:94:97:71:54: ++ fb:cf:f0:37:de:c9:26:c5:dc:1b:9e:89:6d:09:ac: ++ c8:44:71:cb:6d:f1:97:31:d5:4c:20:33:bf:75:4a: ++ a0:e0:dc:69:11:ed:2a:b4:64:10:11:30:8b:0e:b0: ++ a7:10:d8:8a:c5:aa:1b:c8:26:8a:25:e7:66:9f:a5: ++ 6a:1a:2f:7c:5f:83:c6:78:4f:1f + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Key Identifier: +- BC:DD:62:D9:76:DA:1B:D2:54:6B:CF:E0:66:9B:1E:1E:7B:56:0C:0B ++ DD:BF:CA:DA:E6:D1:34:BA:37:75:21:CA:6F:9A:08:28:F2:35:B6:48 + X509v3 Authority Key Identifier: +- keyid:BC:DD:62:D9:76:DA:1B:D2:54:6B:CF:E0:66:9B:1E:1E:7B:56:0C:0B ++ keyid:DD:BF:CA:DA:E6:D1:34:BA:37:75:21:CA:6F:9A:08:28:F2:35:B6:48 + + X509v3 Basic Constraints: + CA:TRUE +- Signature Algorithm: sha1WithRSAEncryption +- 7d:0a:f5:cb:8d:d3:5d:bd:99:8e:f8:2b:0f:ba:eb:c2:d9:a6: +- 27:4f:2e:7b:2f:0e:64:d8:1c:35:50:4e:ee:fc:90:b9:8d:6d: +- a8:c5:c6:06:b0:af:f3:2d:bf:3b:b8:42:07:dd:18:7d:6d:95: +- 54:57:85:18:60:47:2f:eb:78:1b:f9:e8:17:fd:5a:0d:87:17: +- 28:ac:4c:6a:e6:bc:29:f4:f4:55:70:29:42:de:85:ea:ab:6c: +- 23:06:64:30:75:02:8e:53:bc:5e:01:33:37:cc:1e:cd:b8:a4: +- fd:ca:e4:5f:65:3b:83:1c:86:f1:55:02:a0:3a:8f:db:91:b7: +- 40:14:b4:e7:8d:d2:ee:73:ba:e3:e5:34:2d:bc:94:6f:4e:24: +- 06:f7:5f:8b:0e:a7:8e:6b:de:5e:75:f4:32:9a:50:b1:44:33: +- 9a:d0:05:e2:78:82:ff:db:da:8a:63:eb:a9:dd:d1:bf:a0:61: +- ad:e3:9e:8a:24:5d:62:0e:e7:4c:91:7f:ef:df:34:36:3b:2f: +- 5d:f5:84:b2:2f:c4:6d:93:96:1a:6f:30:28:f1:da:12:9a:64: +- b4:40:33:1d:bd:de:2b:53:a8:ea:be:d6:bc:4e:96:f5:44:fb: +- 32:18:ae:d5:1f:f6:69:af:b6:4e:7b:1d:58:ec:3b:a9:53:a3: +- 5e:58:c8:9e ++ Signature Algorithm: sha256WithRSAEncryption ++ 33:6a:54:d3:6b:c0:d7:01:5f:9d:f4:05:c1:93:66:90:50:d0: ++ b7:18:e9:b0:1e:4a:a0:b6:da:76:93:af:84:db:ad:15:54:31: ++ 15:13:e4:de:7e:4e:0c:d5:09:1c:34:35:b6:e5:4c:d6:6f:65: ++ 7d:32:5f:eb:fc:a9:6b:07:f7:49:82:e5:81:7e:07:80:9a:63: ++ f8:2c:c3:40:bc:8f:d4:2a:da:3e:d1:ee:08:b7:4d:a7:84:ca: ++ f4:3f:a1:98:45:be:b1:05:69:e7:df:d7:99:ab:1b:ee:8b:30: ++ cc:f7:fc:e7:d4:0b:17:ae:97:bf:e4:7b:fd:0f:a7:b4:85:79: ++ e3:59:e2:16:87:bf:1f:29:45:2c:23:93:76:be:c0:87:1d:de: ++ ec:2b:42:6a:e5:bb:c8:f4:0a:4a:08:0a:8c:5c:d8:7d:4d:d1: ++ b8:bf:d5:f7:29:ed:92:d1:94:04:e8:35:06:57:7f:2c:23:97: ++ 87:a5:35:8d:26:d3:1a:47:f2:16:d7:d9:c6:d4:1f:23:43:d3: ++ 26:99:39:ca:20:f4:71:23:6f:0c:4a:76:76:f7:76:1f:b3:fe: ++ bf:47:b0:fc:2a:56:81:e1:d2:dd:ee:08:d8:f4:ff:5a:dc:25: ++ 61:8a:91:02:b9:86:1c:f2:50:73:76:25:35:fc:b6:25:26:15: ++ cb:eb:c4:2b:61:0c:1c:e7:ee:2f:17:9b:ec:f0:d4:a1:84:e7: ++ d2:af:de:e4:1b:24:14:a7:01:87:e3:ab:29:58:46:a0:d9:c0: ++ 0a:e0:8d:d7:59:d3:1b:f8:54:20:3e:78:a5:a5:c8:4f:8b:03: ++ c4:96:9f:ec:fb:47:cf:76:2d:8d:65:34:27:bf:fa:ae:01:05: ++ 8a:f3:92:0a:dd:89:6c:97:a1:c7:e7:60:51:e7:ac:eb:4b:7d: ++ 2c:b8:65:c9:fe:5d:6a:48:55:8e:e4:c7:f9:6a:40:e1:b8:64: ++ 45:e9:b5:59:29:a5:5f:cf:7d:58:7d:64:79:e5:a4:09:ac:1e: ++ 76:65:3d:94:c4:68 + -----BEGIN CERTIFICATE----- +-MIIDbTCCAlWgAwIBAgIJALCSZLHy2iHQMA0GCSqGSIb3DQEBBQUAME0xCzAJBgNV ++MIIEbTCCAtWgAwIBAgIJAMstgJlaaVJbMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNV + BAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUgRm91bmRhdGlvbiBDQTEW +-MBQGA1UEAwwNb3VyLWNhLXNlcnZlcjAeFw0xMzAxMDQxOTQ3MDdaFw0yMzAxMDIx +-OTQ3MDdaME0xCzAJBgNVBAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUg +-Rm91bmRhdGlvbiBDQTEWMBQGA1UEAwwNb3VyLWNhLXNlcnZlcjCCASIwDQYJKoZI +-hvcNAQEBBQADggEPADCCAQoCggEBAOfe6eMMnwC2of0rW5bSb8zgvoa5IF7sA3pV +-q+qk6flJhdJm1e3HeupWji2P50LiYiipn9Ybjuu1tJyfFKvf5pSLdh0+bSRh7Qy/ +-AIphDN9cyDZzFgDNR7ptpKR0iIMjChn8Cac8SkvT5x0t5OpMVCHzJtuJNxjUArtA +-Ml+k/y0c99S77I7PXIKs5nwIbEiFYQd/JeBc4Lw0X+C5BEd1yEcLjbzWyGhfM4Ni +-0iBENbGtgRqKzbw1sFyLR9YY6ZwYl8wBPCnM6B7k5MG43ufCERiHWpM02KYl9xRx +-6+QhotIPLi7UYgA109bvXGBLTKkU4t0VWEY3Mya35y5d7ULkxU0CAwEAAaNQME4w +-HQYDVR0OBBYEFLzdYtl22hvSVGvP4GabHh57VgwLMB8GA1UdIwQYMBaAFLzdYtl2 +-2hvSVGvP4GabHh57VgwLMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEB +-AH0K9cuN0129mY74Kw+668LZpidPLnsvDmTYHDVQTu78kLmNbajFxgawr/Mtvzu4 +-QgfdGH1tlVRXhRhgRy/reBv56Bf9Wg2HFyisTGrmvCn09FVwKULeheqrbCMGZDB1 +-Ao5TvF4BMzfMHs24pP3K5F9lO4MchvFVAqA6j9uRt0AUtOeN0u5zuuPlNC28lG9O +-JAb3X4sOp45r3l519DKaULFEM5rQBeJ4gv/b2opj66nd0b+gYa3jnookXWIO50yR +-f+/fNDY7L131hLIvxG2TlhpvMCjx2hKaZLRAMx293itTqOq+1rxOlvVE+zIYrtUf +-9mmvtk57HVjsO6lTo15YyJ4= ++MBQGA1UEAwwNb3VyLWNhLXNlcnZlcjAeFw0xODA4MjkxNDIzMTZaFw0yODA4MjYx ++NDIzMTZaME0xCzAJBgNVBAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUg ++Rm91bmRhdGlvbiBDQTEWMBQGA1UEAwwNb3VyLWNhLXNlcnZlcjCCAaIwDQYJKoZI ++hvcNAQEBBQADggGPADCCAYoCggGBAJftVUG6NheV23Ec0+FhrFhz48aWzysfuAj1 ++nUtLxzD2uAuzUnKgu8lNO47fIo4BV4HJknPMAMbscLA6F0DB3/KMNkzEp4HntiRo ++4qB+NQcvoFv5RUb3HvBGEf7KGjxQ8SapX5winPhB4d9PEpUZL1yQARdufj59z+kJ ++ryX4+EJ3LW1fNvJ4Hn1Kh2hjbAZxG436Jf7U0/WlF7Hv6hfLVMgnmYDLPEXxLFIc ++3R9RRSBQHl6rV3MbQXiW3oSket2PMIU2WHl2oNJhyBuplJljxu74FL+0UlYxl/rr ++rFOelc5MxFpKt8oDJ1s1V84C3OzKafiKWjnLFiAVAyRhbPR6/LZI5VkQXEnQI5/7 ++cV466WifNHKAJ7Y/TLHZ22N/Z2hKbhH46MD0WhY5Uwto3nf6Ref4kc14zSiUl3FU +++8/wN97JJsXcG56JbQmsyERxy23xlzHVTCAzv3VKoODcaRHtKrRkEBEwiw6wpxDY ++isWqG8gmiiXnZp+lahovfF+DxnhPHwIDAQABo1AwTjAdBgNVHQ4EFgQU3b/K2ubR ++NLo3dSHKb5oIKPI1tkgwHwYDVR0jBBgwFoAU3b/K2ubRNLo3dSHKb5oIKPI1tkgw ++DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAYEAM2pU02vA1wFfnfQFwZNm ++kFDQtxjpsB5KoLbadpOvhNutFVQxFRPk3n5ODNUJHDQ1tuVM1m9lfTJf6/ypawf3 ++SYLlgX4HgJpj+CzDQLyP1CraPtHuCLdNp4TK9D+hmEW+sQVp59/Xmasb7oswzPf8 ++59QLF66Xv+R7/Q+ntIV541niFoe/HylFLCOTdr7Ahx3e7CtCauW7yPQKSggKjFzY ++fU3RuL/V9yntktGUBOg1Bld/LCOXh6U1jSbTGkfyFtfZxtQfI0PTJpk5yiD0cSNv ++DEp2dvd2H7P+v0ew/CpWgeHS3e4I2PT/WtwlYYqRArmGHPJQc3YlNfy2JSYVy+vE ++K2EMHOfuLxeb7PDUoYTn0q/e5BskFKcBh+OrKVhGoNnACuCN11nTG/hUID54paXI ++T4sDxJaf7PtHz3YtjWU0J7/6rgEFivOSCt2JbJehx+dgUees60t9LLhlyf5dakhV ++juTH+WpA4bhkRem1WSmlX899WH1keeWkCawedmU9lMRo + -----END CERTIFICATE----- +diff --git a/Lib/test/pythoninfo.py b/Lib/test/pythoninfo.py +index f40ff8d0eb..d588353ce9 100644 +--- a/Lib/test/pythoninfo.py ++++ b/Lib/test/pythoninfo.py +@@ -142,7 +142,7 @@ def collect_platform(info_add): + info_add('platform.python_implementation', + platform.python_implementation()) + info_add('platform.platform', +- platform.platform(aliased=True)) ++ platform.platform(aliased=True, terse=True)) + + + def collect_locale(info_add): +@@ -275,6 +275,14 @@ def collect_readline(info_add): + copy_attributes(info_add, readline, 'readline.%s', attributes, + formatter=format_attr) + ++ if not hasattr(readline, "_READLINE_LIBRARY_VERSION"): ++ # _READLINE_LIBRARY_VERSION has been added to CPython 3.7 ++ doc = getattr(readline, '__doc__', '') ++ if 'libedit readline' in doc: ++ info_add('readline.library', 'libedit readline') ++ elif 'GNU readline' in doc: ++ info_add('readline.library', 'GNU readline') ++ + + def collect_gdb(info_add): + import subprocess +@@ -489,6 +497,34 @@ def collect_test_support(info_add): + call_func(info_add, 'test_support.python_is_optimized', support, 'python_is_optimized') + + ++def collect_cc(info_add): ++ import subprocess ++ import sysconfig ++ ++ CC = sysconfig.get_config_var('CC') ++ if not CC: ++ return ++ ++ try: ++ import shlex ++ args = shlex.split(CC) ++ except ImportError: ++ args = CC.split() ++ args.append('--version') ++ proc = subprocess.Popen(args, ++ stdout=subprocess.PIPE, ++ stderr=subprocess.STDOUT, ++ universal_newlines=True) ++ stdout = proc.communicate()[0] ++ if proc.returncode: ++ # CC --version failed: ignore error ++ return ++ ++ text = stdout.splitlines()[0] ++ text = normalize_text(text) ++ info_add('CC.version', text) ++ ++ + def collect_info(info): + error = False + info_add = info.add +@@ -515,6 +551,7 @@ def collect_info(info): + collect_decimal, + collect_testcapi, + collect_resource, ++ collect_cc, + + # Collecting from tests should be last as they have side effects. + collect_test_socket, +diff --git a/Lib/test/regrtest.py b/Lib/test/regrtest.py +index 6df8f86d95..6b49dafd93 100755 +--- a/Lib/test/regrtest.py ++++ b/Lib/test/regrtest.py +@@ -174,20 +174,21 @@ Pattern examples: + import StringIO + import datetime + import getopt ++import imp + import json ++import math + import os ++import platform + import random + import re + import shutil + import sys ++import sysconfig ++import tempfile + import time + import traceback +-import warnings + import unittest +-import tempfile +-import imp +-import platform +-import sysconfig ++import warnings + + + # Some times __path__ and __file__ are not absolute (e.g. while running from +@@ -248,7 +249,7 @@ PROGRESS_MIN_TIME = 30.0 # seconds + # Display the running tests if nothing happened last N seconds + PROGRESS_UPDATE = 30.0 # seconds + +-from test import test_support ++from test import support + + ALL_RESOURCES = ('audio', 'curses', 'largefile', 'network', 'bsddb', + 'decimal', 'cpu', 'subprocess', 'urlfetch', 'gui', +@@ -270,13 +271,25 @@ def usage(code, msg=''): + + + def format_duration(seconds): +- if seconds < 1.0: +- return '%.0f ms' % (seconds * 1e3) +- if seconds < 60.0: +- return '%.0f sec' % seconds +- +- minutes, seconds = divmod(seconds, 60.0) +- return '%.0f min %.0f sec' % (minutes, seconds) ++ ms = int(math.ceil(seconds * 1e3)) ++ seconds, ms = divmod(ms, 1000) ++ minutes, seconds = divmod(seconds, 60) ++ hours, minutes = divmod(minutes, 60) ++ ++ parts = [] ++ if hours: ++ parts.append('%s hour' % hours) ++ if minutes: ++ parts.append('%s min' % minutes) ++ if seconds: ++ parts.append('%s sec' % seconds) ++ if ms: ++ parts.append('%s ms' % ms) ++ if not parts: ++ return '0 ms' ++ ++ parts = parts[:2] ++ return ' '.join(parts) + + + _FORMAT_TEST_RESULT = { +@@ -317,7 +330,7 @@ def unload_test_modules(save_modules): + # Unload the newly imported modules (best effort finalization) + for module in sys.modules.keys(): + if module not in save_modules and module.startswith("test."): +- test_support.unload(module) ++ support.unload(module) + + + def main(tests=None, testdir=None, verbose=0, quiet=False, +@@ -350,7 +363,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + """ + regrtest_start_time = time.time() + +- test_support.record_original_stdout(sys.stdout) ++ support.record_original_stdout(sys.stdout) + try: + opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:FwWM:j:PGm:', + ['help', 'verbose', 'verbose2', 'verbose3', 'quiet', +@@ -406,7 +419,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + elif o == '--matchfile': + if match_tests is None: + match_tests = [] +- filename = os.path.join(test_support.SAVEDCWD, a) ++ filename = os.path.join(support.SAVEDCWD, a) + with open(filename) as fp: + for line in fp: + match_tests.append(line.strip()) +@@ -439,7 +452,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + if len(huntrleaks) == 2 or not huntrleaks[2]: + huntrleaks[2:] = ["reflog.txt"] + elif o in ('-M', '--memlimit'): +- test_support.set_memlimit(a) ++ support.set_memlimit(a) + elif o in ('-u', '--use'): + u = [x.lower() for x in a.split(',')] + for r in u: +@@ -503,6 +516,15 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + except ValueError: + pass + ++ if huntrleaks: ++ warmup, repetitions, _ = huntrleaks ++ if warmup < 1 or repetitions < 1: ++ msg = ("Invalid values for the --huntrleaks/-R parameters. The " ++ "number of warmups and repetitions must be at least 1 " ++ "each (1:1).") ++ print >>sys.stderr, msg ++ sys.exit(2) ++ + if slaveargs is not None: + args, kwargs = json.loads(slaveargs) + if kwargs['huntrleaks']: +@@ -525,6 +547,8 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + skipped = [] + resource_denieds = [] + environment_changed = [] ++ rerun = [] ++ first_result = None + interrupted = False + + if findleaks: +@@ -552,7 +576,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + + if fromfile: + tests = [] +- fp = open(os.path.join(test_support.SAVEDCWD, fromfile)) ++ fp = open(os.path.join(support.SAVEDCWD, fromfile)) + for line in fp: + guts = line.split() # assuming no test has whitespace in its name + if guts and not guts[0].startswith('#'): +@@ -572,6 +596,12 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + nottests.add(arg) + args = [] + ++ if huntrleaks: ++ # FIXME: bpo-31731: test_io hangs with --huntrleaks ++ print("Warning: bpo-31731: test_io hangs with --huntrleaks: " ++ "exclude the test") ++ nottests.add('test_io') ++ + display_header = (verbose or header or not (quiet or single or tests or args)) and (not pgo) + alltests = findtests(testdir, stdtests, nottests) + selected = tests or args or alltests +@@ -596,7 +626,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + tracer = trace.Trace(trace=False, count=True) + + test_times = [] +- test_support.use_resources = use_resources ++ support.use_resources = use_resources + save_modules = set(sys.modules) + + def accumulate_result(test, result): +@@ -637,8 +667,9 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + def display_progress(test_index, test): + # "[ 51/405/1] test_tcl" + line = "{1:{0}}{2}".format(test_count_width, test_index, test_count) +- if bad and not pgo: +- line = '{}/{}'.format(line, len(bad)) ++ fails = len(bad) + len(environment_changed) ++ if fails and not pgo: ++ line = '{}/{}'.format(line, fails) + line = '[{}]'.format(line) + + # add the system load prefix: "load avg: 1.80 " +@@ -669,6 +700,12 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + if ncpu: + print "== CPU count:", ncpu + ++ if huntrleaks: ++ warmup, repetitions, _ = huntrleaks ++ if warmup < 3: ++ print("WARNING: Running tests with --huntrleaks/-R and less than " ++ "3 warmup repetitions can give false positives!") ++ + if randomize: + random.seed(random_seed) + print "Using random seed", random_seed +@@ -695,7 +732,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + ) + yield (test, args_tuple) + pending = tests_and_args() +- opt_args = test_support.args_from_interpreter_flags() ++ opt_args = support.args_from_interpreter_flags() + base_cmd = [sys.executable] + opt_args + ['-m', 'test.regrtest'] + # required to spawn a new process with PGO flag on/off + if pgo: +@@ -768,7 +805,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + continue + dt = time.time() - worker.start_time + if dt >= PROGRESS_MIN_TIME: +- running.append('%s (%.0f sec)' % (current_test, dt)) ++ running.append('%s (%s)' % (current_test, format_duration(dt))) + return running + + finished = 0 +@@ -782,6 +819,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + running = get_running(workers) + if running and not pgo: + print('running: %s' % ', '.join(running)) ++ sys.stdout.flush() + continue + + test, stdout, stderr, result = item +@@ -795,14 +833,14 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + if (ok not in (CHILD_ERROR, INTERRUPTED) + and test_time >= PROGRESS_MIN_TIME + and not pgo): +- text += ' (%.0f sec)' % test_time ++ text += ' (%s)' % format_duration(test_time) + running = get_running(workers) + if running and not pgo: + text += ' -- running: %s' % ', '.join(running) + display_progress(test_index, text) + + if stdout: +- print stdout ++ print(stdout) + sys.stdout.flush() + if stderr and not pgo: + print >>sys.stderr, stderr +@@ -880,56 +918,102 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + + unload_test_modules(save_modules) + +- if interrupted and not pgo: ++ ++ def get_tests_result(): ++ result = [] ++ if bad: ++ result.append("FAILURE") ++ elif fail_env_changed and environment_changed: ++ result.append("ENV CHANGED") ++ ++ if interrupted: ++ result.append("INTERRUPTED") ++ ++ if not result: ++ result.append("SUCCESS") ++ ++ result = ', '.join(result) ++ if first_result: ++ result = '%s then %s' % (first_result, result) ++ return result ++ ++ ++ def display_result(): + # print a newline after ^C + print +- print "Test suite interrupted by signal SIGINT." +- omitted = set(selected) - set(good) - set(bad) - set(skipped) +- print count(len(omitted), "test"), "omitted:" +- printlist(omitted) +- if good and not quiet and not pgo: +- if not bad and not skipped and not interrupted and len(good) > 1: +- print "All", +- print count(len(good), "test"), "OK." +- if print_slow: +- test_times.sort(reverse=True) +- print "10 slowest tests:" +- for test_time, test in test_times[:10]: +- print("- %s: %.1fs" % (test, test_time)) +- if bad and not pgo: +- print count(len(bad), "test"), "failed:" +- printlist(bad) +- if environment_changed and not pgo: +- print "{} altered the execution environment:".format( +- count(len(environment_changed), "test")) +- printlist(environment_changed) +- if skipped and not quiet and not pgo: +- print count(len(skipped), "test"), "skipped:" +- printlist(skipped) +- +- e = _ExpectedSkips() +- plat = sys.platform +- if e.isvalid(): +- surprise = set(skipped) - e.getexpected() - set(resource_denieds) +- if surprise: +- print count(len(surprise), "skip"), \ +- "unexpected on", plat + ":" +- printlist(surprise) ++ print("== Tests result: %s ==" % get_tests_result()) ++ ++ if interrupted and not pgo: ++ print ++ print "Test suite interrupted by signal SIGINT." ++ omitted = set(selected) - set(good) - set(bad) - set(skipped) ++ print count(len(omitted), "test"), "omitted:" ++ printlist(omitted) ++ ++ if good and not quiet and not pgo: ++ print ++ if not bad and not skipped and not interrupted and len(good) > 1: ++ print "All", ++ print count(len(good), "test"), "OK." ++ ++ if print_slow: ++ test_times.sort(reverse=True) ++ print ++ print "10 slowest tests:" ++ for test_time, test in test_times[:10]: ++ print("- %s: %.1fs" % (test, test_time)) ++ ++ if bad and not pgo: ++ print ++ print count(len(bad), "test"), "failed:" ++ printlist(bad) ++ ++ if environment_changed and not pgo: ++ print ++ print "{} altered the execution environment:".format( ++ count(len(environment_changed), "test")) ++ printlist(environment_changed) ++ ++ if skipped and not quiet and not pgo: ++ print ++ print count(len(skipped), "test"), "skipped:" ++ printlist(skipped) ++ ++ e = _ExpectedSkips() ++ plat = sys.platform ++ if e.isvalid(): ++ surprise = set(skipped) - e.getexpected() - set(resource_denieds) ++ if surprise: ++ print count(len(surprise), "skip"), \ ++ "unexpected on", plat + ":" ++ printlist(surprise) ++ else: ++ print "Those skips are all expected on", plat + "." + else: +- print "Those skips are all expected on", plat + "." +- else: +- print "Ask someone to teach regrtest.py about which tests are" +- print "expected to get skipped on", plat + "." ++ print "Ask someone to teach regrtest.py about which tests are" ++ print "expected to get skipped on", plat + "." ++ ++ if rerun: ++ print ++ print("%s:" % count(len(rerun), "re-run test")) ++ printlist(rerun) ++ ++ ++ display_result() + + if verbose2 and bad: ++ first_result = get_tests_result() ++ ++ print + print "Re-running failed tests in verbose mode" +- for test in bad[:]: ++ rerun = bad[:] ++ for test in rerun: + print "Re-running test %r in verbose mode" % test + sys.stdout.flush() + try: +- test_support.verbose = True ++ support.verbose = True + ok = runtest(test, True, quiet, huntrleaks, None, pgo, +- testdir=testdir) ++ match_tests=match_tests, testdir=testdir) + except KeyboardInterrupt: + # print a newline separate from the ^C + print +@@ -942,6 +1026,8 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + print count(len(bad), "test"), "failed again:" + printlist(bad) + ++ display_result() ++ + if single: + if next_single_test: + with open(filename, 'w') as fp: +@@ -960,15 +1046,7 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, + duration = time.time() - regrtest_start_time + print("Total duration: %s" % format_duration(duration)) + +- if bad: +- result = "FAILURE" +- elif interrupted: +- result = "INTERRUPTED" +- elif fail_env_changed and environment_changed: +- result = "ENV CHANGED" +- else: +- result = "SUCCESS" +- print("Tests result: %s" % result) ++ print("Tests result: %s" % get_tests_result()) + + if bad: + sys.exit(2) +@@ -1033,13 +1111,17 @@ def runtest(test, verbose, quiet, + PASSED test passed + """ + +- test_support.verbose = verbose # Tell tests to be moderately quiet ++ support.verbose = verbose # Tell tests to be moderately quiet + if use_resources is not None: +- test_support.use_resources = use_resources ++ support.use_resources = use_resources + try: +- test_support.set_match_tests(match_tests) ++ support.set_match_tests(match_tests) ++ # reset the environment_altered flag to detect if a test altered ++ # the environment ++ support.environment_altered = False + if failfast: +- test_support.failfast = True ++ support.failfast = True ++ + return runtest_inner(test, verbose, quiet, huntrleaks, pgo, testdir) + finally: + cleanup_test_droppings(test, verbose) +@@ -1139,31 +1221,31 @@ class saved_test_environment: + asyncore.close_all(ignore_all=True) + asyncore.socket_map.update(saved_map) + +- def get_test_support_TESTFN(self): +- if os.path.isfile(test_support.TESTFN): ++ def get_support_TESTFN(self): ++ if os.path.isfile(support.TESTFN): + result = 'f' +- elif os.path.isdir(test_support.TESTFN): ++ elif os.path.isdir(support.TESTFN): + result = 'd' + else: + result = None + return result +- def restore_test_support_TESTFN(self, saved_value): ++ def restore_support_TESTFN(self, saved_value): + if saved_value is None: +- if os.path.isfile(test_support.TESTFN): +- os.unlink(test_support.TESTFN) +- elif os.path.isdir(test_support.TESTFN): +- shutil.rmtree(test_support.TESTFN) ++ if os.path.isfile(support.TESTFN): ++ os.unlink(support.TESTFN) ++ elif os.path.isdir(support.TESTFN): ++ shutil.rmtree(support.TESTFN) + + def get_files(self): + return sorted(fn + ('/' if os.path.isdir(fn) else '') + for fn in os.listdir(os.curdir)) + def restore_files(self, saved_value): +- fn = test_support.TESTFN ++ fn = support.TESTFN + if fn not in saved_value and (fn + '/') not in saved_value: + if os.path.isfile(fn): +- test_support.unlink(fn) ++ support.unlink(fn) + elif os.path.isdir(fn): +- test_support.rmtree(fn) ++ support.rmtree(fn) + + def resource_info(self): + for name in self.resources: +@@ -1180,6 +1262,10 @@ class saved_test_environment: + def __exit__(self, exc_type, exc_val, exc_tb): + saved_values = self.saved_values + del self.saved_values ++ ++ # Read support.environment_altered, set by support helper functions ++ self.changed |= support.environment_altered ++ + for name, get, restore in self.resource_info(): + current = get() + original = saved_values.pop(name) +@@ -1202,10 +1288,10 @@ class saved_test_environment: + + + def post_test_cleanup(): +- test_support.reap_children() ++ support.reap_children() + + def runtest_inner(test, verbose, quiet, huntrleaks=False, pgo=False, testdir=None): +- test_support.unload(test) ++ support.unload(test) + if verbose: + capture_stdout = None + else: +@@ -1231,16 +1317,17 @@ def runtest_inner(test, verbose, quiet, huntrleaks=False, pgo=False, testdir=Non + # being imported. For tests based on unittest or doctest, + # explicitly invoke their test_main() function (if it exists). + indirect_test = getattr(the_module, "test_main", None) +- if indirect_test is not None: +- indirect_test() + if huntrleaks: + refleak = dash_R(the_module, test, indirect_test, + huntrleaks) ++ else: ++ if indirect_test is not None: ++ indirect_test() + test_time = time.time() - start_time + post_test_cleanup() + finally: + sys.stdout = save_stdout +- except test_support.ResourceDenied, msg: ++ except support.ResourceDenied, msg: + if not quiet and not pgo: + print test, "skipped --", msg + sys.stdout.flush() +@@ -1252,7 +1339,7 @@ def runtest_inner(test, verbose, quiet, huntrleaks=False, pgo=False, testdir=Non + return SKIPPED, test_time + except KeyboardInterrupt: + raise +- except test_support.TestFailed, msg: ++ except support.TestFailed, msg: + if not pgo: + print >>sys.stderr, "test", test, "failed --", msg + sys.stderr.flush() +@@ -1297,7 +1384,7 @@ def cleanup_test_droppings(testname, verbose): + # since if a test leaves a file open, it cannot be deleted by name (while + # there's nothing we can do about that here either, we can display the + # name of the offending test, which is a real help). +- for name in (test_support.TESTFN, ++ for name in (support.TESTFN, + "db_home", + ): + if not os.path.exists(name): +@@ -1364,39 +1451,61 @@ def dash_R(the_module, test, indirect_test, huntrleaks): + + deltas = [] + nwarmup, ntracked, fname = huntrleaks +- fname = os.path.join(test_support.SAVEDCWD, fname) ++ fname = os.path.join(support.SAVEDCWD, fname) + repcount = nwarmup + ntracked ++ rc_deltas = [0] * ntracked ++ fd_deltas = [0] * ntracked ++ + print >> sys.stderr, "beginning", repcount, "repetitions" + print >> sys.stderr, ("1234567890"*(repcount//10 + 1))[:repcount] + dash_R_cleanup(fs, ps, pic, zdc, abcs) ++ # initialize variables to make pyflakes quiet ++ rc_before = fd_before = 0 + for i in range(repcount): +- rc_before = sys.gettotalrefcount() + run_the_test() + sys.stderr.write('.') + dash_R_cleanup(fs, ps, pic, zdc, abcs) + rc_after = sys.gettotalrefcount() ++ fd_after = support.fd_count() + if i >= nwarmup: +- deltas.append(rc_after - rc_before) ++ rc_deltas[i - nwarmup] = rc_after - rc_before ++ fd_deltas[i - nwarmup] = fd_after - fd_before ++ rc_before = rc_after ++ fd_before = fd_after + print >> sys.stderr + +- # bpo-30776: Try to ignore false positives: +- # +- # [3, 0, 0] +- # [0, 1, 0] +- # [8, -8, 1] +- # +- # Expected leaks: +- # +- # [5, 5, 6] +- # [10, 1, 1] +- if all(delta >= 1 for delta in deltas): +- msg = '%s leaked %s references, sum=%s' % (test, deltas, sum(deltas)) +- print >> sys.stderr, msg +- with open(fname, "a") as refrep: +- print >> refrep, msg +- refrep.flush() +- return True +- return False ++ # These checkers return False on success, True on failure ++ def check_rc_deltas(deltas): ++ # Checker for reference counters and memomry blocks. ++ # ++ # bpo-30776: Try to ignore false positives: ++ # ++ # [3, 0, 0] ++ # [0, 1, 0] ++ # [8, -8, 1] ++ # ++ # Expected leaks: ++ # ++ # [5, 5, 6] ++ # [10, 1, 1] ++ return all(delta >= 1 for delta in deltas) ++ ++ def check_fd_deltas(deltas): ++ return any(deltas) ++ ++ failed = False ++ for deltas, item_name, checker in [ ++ (rc_deltas, 'references', check_rc_deltas), ++ (fd_deltas, 'file descriptors', check_fd_deltas) ++ ]: ++ if checker(deltas): ++ msg = '%s leaked %s %s, sum=%s' % (test, deltas, item_name, sum(deltas)) ++ print >> sys.stderr, msg ++ with open(fname, "a") as refrep: ++ print >> refrep, msg ++ refrep.flush() ++ failed = True ++ return failed + + def dash_R_cleanup(fs, ps, pic, zdc, abcs): + import gc, copy_reg +@@ -1580,12 +1689,12 @@ def _list_cases(suite): + if isinstance(test, unittest.TestSuite): + _list_cases(test) + elif isinstance(test, unittest.TestCase): +- if test_support.match_test(test): ++ if support.match_test(test): + print(test.id()) + + def list_cases(testdir, selected, match_tests): +- test_support.verbose = False +- test_support.set_match_tests(match_tests) ++ support.verbose = False ++ support.set_match_tests(match_tests) + + save_modules = set(sys.modules) + skipped = [] +@@ -2019,8 +2128,8 @@ def main_in_temp_cwd(): + # Run the tests in a context manager that temporary changes the CWD to a + # temporary and writable directory. If it's not possible to create or + # change the CWD, the original CWD will be used. The original CWD is +- # available from test_support.SAVEDCWD. +- with test_support.temp_cwd(TESTCWD, quiet=True): ++ # available from support.SAVEDCWD. ++ with support.temp_cwd(TESTCWD, quiet=True): + main() + + if __name__ == '__main__': +diff --git a/Lib/test/revocation.crl b/Lib/test/revocation.crl +index 6d89b08ebe..c05461ca7f 100644 +--- a/Lib/test/revocation.crl ++++ b/Lib/test/revocation.crl +@@ -1,11 +1,14 @@ + -----BEGIN X509 CRL----- +-MIIBpjCBjwIBATANBgkqhkiG9w0BAQUFADBNMQswCQYDVQQGEwJYWTEmMCQGA1UE ++MIICJjCBjwIBATANBgkqhkiG9w0BAQsFADBNMQswCQYDVQQGEwJYWTEmMCQGA1UE + CgwdUHl0aG9uIFNvZnR3YXJlIEZvdW5kYXRpb24gQ0ExFjAUBgNVBAMMDW91ci1j +-YS1zZXJ2ZXIXDTEzMTEyMTE3MDg0N1oXDTIzMDkzMDE3MDg0N1qgDjAMMAoGA1Ud +-FAQDAgEAMA0GCSqGSIb3DQEBBQUAA4IBAQCNJXC2mVKauEeN3LlQ3ZtM5gkH3ExH +-+i4bmJjtJn497WwvvoIeUdrmVXgJQR93RtV37hZwN0SXMLlNmUZPH4rHhihayw4m +-unCzVj/OhCCY7/TPjKuJ1O/0XhaLBpBVjQN7R/1ujoRKbSia/CD3vcn7Fqxzw7LK +-fSRCKRGTj1CZiuxrphtFchwALXSiFDy9mr2ZKhImcyq1PydfgEzU78APpOkMQsIC +-UNJ/cf3c9emzf+dUtcMEcejQ3mynBo4eIGg1EW42bz4q4hSjzQlKcBV0muw5qXhc +-HOxH2iTFhQ7SrvVuK/dM14rYM4B5mSX3nRC1kNmXpS9j3wJDhuwmjHed ++YS1zZXJ2ZXIXDTE4MDgyOTE0MjMxNloXDTI4MDcwNzE0MjMxNlqgDjAMMAoGA1Ud ++FAQDAgEAMA0GCSqGSIb3DQEBCwUAA4IBgQCPhrtGSbuvxPAI3YWQFDB4iOWdBnVk ++ugW1lsifmCsE86FfID0EwUut1SRHlksltMtcoULMEIdu8yMLWci++4ve22EEuMKT ++HUc3T/wBIuQUhA7U4deFG8CZPAxRpNoK470y7dkD4OVf0Gxa6WYDl9z8mXKmWCB9 ++hvzqVfLWNSLTAVPsHtkD5PXdi5yRkQr6wYD7poWaIvkpsn7EKCY6Tw5V3rsbRuZq ++AGVCq5TH3mctcmwLloCJ4Xr/1q0DsRrYxeeLYxE+UpvvCbVBKgtjBK7zINS7AbcJ ++CYCYKUwGWv1fYKJ+KQQHf75mT3jQ9lWuzOj/YWK4k1EBnYmVGuKKt73lLFxC6h3y ++MUnaBZc1KZSyJj0IxfHg/o6qx8NgKOl9XRIQ5g5B30cwpPOskGhEhodbTTY3bPtm ++RQ36JvQZngzmkhyhr+MDEV5yUTOShfUiclzQOx26CmLmLHWxOZgXtFZob/oKrvbm ++Gen/+7K7YTw6hfY52U7J2FuQRGOyzBXfBYQ= + -----END X509 CRL----- +diff --git a/Lib/test/ssl_cert.pem b/Lib/test/ssl_cert.pem +index 47a7d7e37e..de596717bd 100644 +--- a/Lib/test/ssl_cert.pem ++++ b/Lib/test/ssl_cert.pem +@@ -1,15 +1,26 @@ + -----BEGIN CERTIFICATE----- +-MIICVDCCAb2gAwIBAgIJANfHOBkZr8JOMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNV +-BAYTAlhZMRcwFQYDVQQHEw5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9u +-IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xMDEw +-MDgyMzAxNTZaFw0yMDEwMDUyMzAxNTZaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQH +-Ew5DYXN0bGUgQW50aHJheDEjMCEGA1UEChMaUHl0aG9uIFNvZnR3YXJlIEZvdW5k +-YXRpb24xEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw +-gYkCgYEA21vT5isq7F68amYuuNpSFlKDPrMUCa4YWYqZRt2OZ+/3NKaZ2xAiSwr7 +-6MrQF70t5nLbSPpqE5+5VrS58SY+g/sXLiFd6AplH1wJZwh78DofbFYXUggktFMt +-pTyiX8jtP66bkcPkDADA089RI1TQR6Ca+n7HFa7c1fabVV6i3zkCAwEAAaMYMBYw +-FAYDVR0RBA0wC4IJbG9jYWxob3N0MA0GCSqGSIb3DQEBBQUAA4GBAHPctQBEQ4wd +-BJ6+JcpIraopLn8BGhbjNWj40mmRqWB/NAWF6M5ne7KpGAu7tLeG4hb1zLaldK8G +-lxy2GPSRF6LFS48dpEj2HbMv2nvv6xxalDMJ9+DicWgAKTQ6bcX2j3GUkCR0g/T1 +-CRlNBAAlvhKzO7Clpf9l0YKBEfraJByX ++MIIEWTCCAsGgAwIBAgIJAJinz4jHSjLtMA0GCSqGSIb3DQEBCwUAMF8xCzAJBgNV ++BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u ++IFNvZnR3YXJlIEZvdW5kYXRpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xODA4 ++MjkxNDIzMTVaFw0yODA4MjYxNDIzMTVaMF8xCzAJBgNVBAYTAlhZMRcwFQYDVQQH ++DA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9uIFNvZnR3YXJlIEZvdW5k ++YXRpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDCCAaIwDQYJKoZIhvcNAQEBBQADggGP ++ADCCAYoCggGBALKUqUtopT6E68kN+uJNEt34i2EbmG/bwjcD8IaMsgJPSsMO2Bpd ++3S6qWgkCeOyCfmAwBxK2kNbxGb63ouysEv7l8GCTJTWv3hG/HQcejJpnAEGi6K1U ++fDbyE/db6yZ12SoHVTGkadN4vYGCPd1Wj9ZO1F877SHQ8rDWX3xgTWkxN2ojBw44 ++T8RHSDiG8D/CvG4uEy+VUszL+Uvny5y2poNSqvI3J56sptWSrh8nIIbkPZPBdUne ++LYMOHTFK3ZjXSmhlXgziTxK71nnzM3Y9K9gxPnRqoXbvu/wFo55hQCkETiRkYgmm ++jXcBMZ0TClQVnQWuLjMthRnWFZs4Lfmwqjs7FZD/61581R2BYehvpWbLvvuOJhwv ++DFzexL2sXcAl7SsxbzeQKRHqGbIDfbnQTXfs3/VC6Ye5P82P2ucj+XC32N9piRmO ++gCBP8L3ub+YzzdxikZN2gZXXE2jsb3QyE/R2LkWdWyshpKe+RsZP1SBRbHShUyOh ++yJ90baoiEwj2mwIDAQABoxgwFjAUBgNVHREEDTALgglsb2NhbGhvc3QwDQYJKoZI ++hvcNAQELBQADggGBAHRUO/UIHl3jXQENewYayHxkIx8t7nu40iO2DXbicSijz5bo ++5//xAB6RxhBAlsDBehgQP1uoZg+WJW+nHu3CIVOU3qZNZRaozxiCl2UFKcNqLOmx ++R3NKpo1jYf4REQIeG8Yw9+hSWLRbshNteP6bKUUf+vanhg9+axyOEOH/iOQvgk/m ++b8wA8wNa4ujWljPbTQnj7ry8RqhTM0GcAN5LSdSvcKcpzLcs3aYwh+Z8e30sQWna ++F40sa5u7izgBTOrwpcDm/w5kC46vpRQ5fnbshVw6pne2by0mdMECASid/p25N103 ++jMqTFlmO7kpf/jpCSmamp3/JSEE1BJKHwQ6Ql4nzRA2N1mnvWH7Zxcv043gkHeAu ++0x8evpvwuhdIyproejNFlBpKmW8OX7yKTCPPMC/VkX8Q1rVkxU0DQ6hmvwZlhoKa ++9Wc2uXpw9xF8itV4Uvcdr3dwqByvIqn7iI/gB+4l41e0u8OmH2MKOx4Nxlly5TNW ++HcVKQHyOeyvnINuBAQ== + -----END CERTIFICATE----- +diff --git a/Lib/test/ssl_key.passwd.pem b/Lib/test/ssl_key.passwd.pem +index 2524672e70..e4f1370ab2 100644 +--- a/Lib/test/ssl_key.passwd.pem ++++ b/Lib/test/ssl_key.passwd.pem +@@ -1,18 +1,42 @@ + -----BEGIN RSA PRIVATE KEY----- + Proc-Type: 4,ENCRYPTED +-DEK-Info: DES-EDE3-CBC,1A8D9D2A02EC698A ++DEK-Info: DES-EDE3-CBC,8064BE1494B24B13 + +-kJYbfZ8L0sfe9Oty3gw0aloNnY5E8fegRfQLZlNoxTl6jNt0nIwI8kDJ36CZgR9c +-u3FDJm/KqrfUoz8vW+qEnWhSG7QPX2wWGPHd4K94Yz/FgrRzZ0DoK7XxXq9gOtVA +-AVGQhnz32p+6WhfGsCr9ArXEwRZrTk/FvzEPaU5fHcoSkrNVAGX8IpSVkSDwEDQr +-Gv17+cfk99UV1OCza6yKHoFkTtrC+PZU71LomBabivS2Oc4B9hYuSR2hF01wTHP+ +-YlWNagZOOVtNz4oKK9x9eNQpmfQXQvPPTfusexKIbKfZrMvJoxcm1gfcZ0H/wK6P +-6wmXSG35qMOOztCZNtperjs1wzEBXznyK8QmLcAJBjkfarABJX9vBEzZV0OUKhy+ +-noORFwHTllphbmydLhu6ehLUZMHPhzAS5UN7srtpSN81eerDMy0RMUAwA7/PofX1 +-94Me85Q8jP0PC9ETdsJcPqLzAPETEYu0ELewKRcrdyWi+tlLFrpE5KT/s5ecbl9l +-7B61U4Kfd1PIXc/siINhU3A3bYK+845YyUArUOnKf1kEox7p1RpD7yFqVT04lRTo +-cibNKATBusXSuBrp2G6GNuhWEOSafWCKJQAzgCYIp6ZTV2khhMUGppc/2H3CF6cO +-zX0KtlPVZC7hLkB6HT8SxYUwF1zqWY7+/XPPdc37MeEZ87Q3UuZwqORLY+Z0hpgt +-L5JXBCoklZhCAaN2GqwFLXtGiRSRFGY7xXIhbDTlE65Wv1WGGgDLMKGE1gOz3yAo +-2jjG1+yAHJUdE69XTFHSqSkvaloA1W03LdMXZ9VuQJ/ySXCie6ABAQ== ++KJrffOMbo8M0I3PzcYxRZGMpKD1yB3Ii4+bT5XoanxjIJ+4fdx6LfZ0Rsx+riyzs ++tymsQu/iYY9j+4rCvN9+eetsL1X6iZpiimKsLexcid9M3fb0vxED5Sgw0dvunCUA ++xhqjLIKR92MKbODHf6KrDKCpsiPbjq4gZ7P+uCGXAMHL3MXIJSC0hW9rK7Ce6oyO ++CjpIcgB8x+GUWZZZhAFdlzIHMZrteNP2P5HK6QcaT71P034Dz1hhqoj4Q0t+Fta2 ++4tfsM/bnTR/l6hwlhPa1e3Uj322tDTDWBScgWANn5+sEWldLmozMaWhZsn22pfk2 ++KjRMGXG024JVheV882nbdOBvG7oq+lxkZ/ZP+vvqJqnvYtf7WtM8UivzYpe5Hz5b ++kVvWzPjBLUSZ9whM9rDLqSSqMPyPvDTuEmLkuq+xm7pYJmsLqIMP2klZLqRxLX6K ++uqwplb8UG440qauxgnQ905PId1l2fJEnRtV+7vXprA0L0QotgXLVHBhLmTFM+3PH ++9H3onf31dionUAPrn3nfVE36HhvVgRyvDBnBzJSIMighgq21Qx/d1dk0DRYi1hUI ++nCHl0YJPXheVcXR7JiSF2XQCAaFuS1Mr7NCXfWZOZQC/0dkvmHnl9DUAhuqq9BNZ ++1cKhZXcKHadg2/r0Zup/oDzmHPUEfTAXT0xbqoWlhkdwbF2veWQ96A/ncx3ISTb4 ++PkXBlX9rdia8nmtyQDQRn4NuvchbaGkj4WKFC8pF8Hn7naHqwjpHaDUimBc0CoQW ++edNJqruKWwtSVLuwKHCC2gZFX9AXSKJXJz/QRSUlhFGOhuF/J6yKaXj6n5lxWNiQ ++54J+OP/hz2aS95CD2+Zf1SKpxdWiLZSIQqESpmmUrXROixNJZ/Z7gI74Dd9dSJOH ++W+3AU03vrrFZVrJVZhjcINHoH1Skh6JKscH18L6x4U868nSr4SrRLX8BhHllOQyD ++bmU+PZAjF8ZBIaCtTGulDXD29F73MeAZeTSsgQjFu0iKLj1wPiphbx8i/SUtR4YP ++X6PVA04g66r1NBw+3RQASVorZ3g1MSFvITHXcbKkBDeJH2z1+c6t/VVyTONnQhM5 ++lLgRSk6HCbetvT9PKxWrWutA12pdBYEHdZhMHVf2+xclky7l09w8hg2/qqcdGRGe ++oAOZ72t0l5ObNyaruDKUS6f4AjOyWq/Xj5xuFtf1n3tQHyslSyCTPcAbQhDfTHUx ++vixb/V9qvYPt7OCn8py7v1M69NH42QVFAvwveDIFjZdqfIKBoJK2V4qPoevJI6uj ++Q5ByMt8OXOjSXNpHXpYQWUiWeCwOEBXJX8rzCHdMtg37jJ0zCmeErR1NTdg+EujM ++TWYgd06jlT67tURST0aB2kg4ijKgUJefD313LW1zC6gVsTbjSZxYyRbPfSP6flQB ++yCi1C19E2OsgleqbkBVC5GlYUzaJT7SGjCRmGx1eqtbrALu+LVH24Wceexlpjydl +++s2nf/DZlKun/tlPh6YioifPCJjByZMQOCEfIox6BkemZETz8uYA4TTWimG13Z03 ++gyDGC2jdpEW414J2qcQDvrdUgJ+HlhrAAHaWpMQDbXYxBGoZ+3+ORvQV4kAsCwL8 ++k3EIrVpePdik+1xgOWsyLj6QxFXlTMvL6Wc5pnArFPORsgHEolJvxSPTf9aAHNPn ++V2WBvxiLBtYpGrujAUM40Syx/aN2RPtcXYPAusHUBw+S8/p+/8Kg8GZmnIXG3F89 ++45Eepl2quZYIrou7a1fwIpIIZ0hFiBQ1mlHVMFtxwVHS1bQb3SU2GeO+JcGjdVXc ++04qeGuQ5M164eQ5C0T7ZQ1ULiUlFWKD30m+cjqmZzt3d7Q0mKpMKuESIuZJo/wpD ++Nas432aLKUhcNx/pOYLkKJRpGZKOupQoD5iUj/j44o8JoFkDK33v2S57XB5QGz28 ++9Zuhx49b3W8mbM6EBanlQKLWJGCxXqc/jhYhFWn+b0MhidynFgA0oeWvf6ZDyt6H ++Yi5Etxsar09xp0Do3NxtQXLuSUu0ji2pQzSIKuoqQWKqldm6VrpwojiqJhy4WQBQ ++aVVyFeWBC7G3Zj76dO+yp2sfJ0itJUQ8AIB9Cg0f34rEZu+r9luPmqBoUeL95Tk7 ++YvCOU3Jl8Iqysv8aNpVXT8sa8rrSbruWCByEePZ37RIdHLMVBwVY0eVaFQjrjU7E ++mXmM9eaoYLfXOllsQ+M2+qPFUITr/GU3Qig13DhK/+yC1R6V2a0l0WRhMltIPYKW ++Ztvvr4hK5LcYCeS113BLiMbDIMMZZYGDZGMdC8DnnVbT2loF0Rfmp80Af31KmMQ4 ++6XvMatW9UDjBoY5a/YMpdm7SRwm+MgV2KNPpc2kST87/yi9oprGAb8qiarHiHTM0 + -----END RSA PRIVATE KEY----- +diff --git a/Lib/test/ssl_key.pem b/Lib/test/ssl_key.pem +index 3fd3bbd54a..1ea4578d81 100644 +--- a/Lib/test/ssl_key.pem ++++ b/Lib/test/ssl_key.pem +@@ -1,16 +1,40 @@ + -----BEGIN PRIVATE KEY----- +-MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANtb0+YrKuxevGpm +-LrjaUhZSgz6zFAmuGFmKmUbdjmfv9zSmmdsQIksK++jK0Be9LeZy20j6ahOfuVa0 +-ufEmPoP7Fy4hXegKZR9cCWcIe/A6H2xWF1IIJLRTLaU8ol/I7T+um5HD5AwAwNPP +-USNU0Eegmvp+xxWu3NX2m1Veot85AgMBAAECgYA3ZdZ673X0oexFlq7AAmrutkHt +-CL7LvwrpOiaBjhyTxTeSNWzvtQBkIU8DOI0bIazA4UreAFffwtvEuPmonDb3F+Iq +-SMAu42XcGyVZEl+gHlTPU9XRX7nTOXVt+MlRRRxL6t9GkGfUAXI3XxJDXW3c0vBK +-UL9xqD8cORXOfE06rQJBAP8mEX1ERkR64Ptsoe4281vjTlNfIbs7NMPkUnrn9N/Y +-BLhjNIfQ3HFZG8BTMLfX7kCS9D593DW5tV4Z9BP/c6cCQQDcFzCcVArNh2JSywOQ +-ZfTfRbJg/Z5Lt9Fkngv1meeGNPgIMLN8Sg679pAOOWmzdMO3V706rNPzSVMME7E5 +-oPIfAkEA8pDddarP5tCvTTgUpmTFbakm0KoTZm2+FzHcnA4jRh+XNTjTOv98Y6Ik +-eO5d1ZnKXseWvkZncQgxfdnMqqpj5wJAcNq/RVne1DbYlwWchT2Si65MYmmJ8t+F +-0mcsULqjOnEMwf5e+ptq5LzwbyrHZYq5FNk7ocufPv/ZQrcSSC+cFwJBAKvOJByS +-x56qyGeZLOQlWS2JS3KJo59XuLFGqcbgN9Om9xFa41Yb4N9NvplFivsvZdw3m1Q/ +-SPIXQuT8RMPDVNQ= ++MIIG/wIBADANBgkqhkiG9w0BAQEFAASCBukwggblAgEAAoIBgQCylKlLaKU+hOvJ ++DfriTRLd+IthG5hv28I3A/CGjLICT0rDDtgaXd0uqloJAnjsgn5gMAcStpDW8Rm+ ++t6LsrBL+5fBgkyU1r94Rvx0HHoyaZwBBouitVHw28hP3W+smddkqB1UxpGnTeL2B ++gj3dVo/WTtRfO+0h0PKw1l98YE1pMTdqIwcOOE/ER0g4hvA/wrxuLhMvlVLMy/lL ++58uctqaDUqryNyeerKbVkq4fJyCG5D2TwXVJ3i2DDh0xSt2Y10poZV4M4k8Su9Z5 ++8zN2PSvYMT50aqF277v8BaOeYUApBE4kZGIJpo13ATGdEwpUFZ0Fri4zLYUZ1hWb ++OC35sKo7OxWQ/+tefNUdgWHob6Vmy777jiYcLwxc3sS9rF3AJe0rMW83kCkR6hmy ++A3250E137N/1QumHuT/Nj9rnI/lwt9jfaYkZjoAgT/C97m/mM83cYpGTdoGV1xNo ++7G90MhP0di5FnVsrIaSnvkbGT9UgUWx0oVMjocifdG2qIhMI9psCAwEAAQKCAYBT ++sHmaPmNaZj59jZCqp0YVQlpHWwBYQ5vD3pPE6oCttm0p9nXt/VkfenQRTthOtmT1 ++POzDp00/feP7zeGLmqSYUjgRekPw4gdnN7Ip2PY5kdW77NWwDSzdLxuOS8Rq1MW9 ++/Yu+ZPe3RBlDbT8C0IM+Atlh/BqIQ3zIxN4g0pzUlF0M33d6AYfYSzOcUhibOO7H ++j84r+YXBNkIRgYKZYbutRXuZYaGuqejRpBj3voVu0d3Ntdb6lCWuClpB9HzfGN0c ++RTv8g6UYO4sK3qyFn90ibIR/1GB9watvtoWVZqggiWeBzSWVWRsGEf9O+Cx4oJw1 ++IphglhmhbgNksbj7bD24on/icldSOiVkoUemUOFmHWhCm4PnB1GmbD8YMfEdSbks ++qDr1Ps1zg4mGOinVD/4cY7vuPFO/HCH07wfeaUGzRt4g0/yLr+XjVofOA3oowyxv ++JAzr+niHA3lg5ecj4r7M68efwzN1OCyjMrVJw2RAzwvGxE+rm5NiT08SWlKQZnkC ++gcEA4wvyLpIur/UB84nV3XVJ89UMNBLm++aTFzld047BLJtMaOhvNqx6Cl5c8VuW ++l261KHjiVzpfNM3/A2LBQJcYkhX7avkqEXlj57cl+dCWAVwUzKmLJTPjfaTTZnYJ ++xeN3dMYjJz2z2WtgvfvDoJLukVwIMmhTY8wtqqYyQBJ/l06pBsfw5TNvmVIOQHds ++8ASOiFt+WRLk2bl9xrGGayqt3VV93KVRzF27cpjOgEcG74F3c0ZW9snERN7vIYwB ++JfrlAoHBAMlahPwMP2TYylG8OzHe7EiehTekSO26LGh0Cq3wTGXYsK/q8hQCzL14 ++kWW638vpwXL6L9ntvrd7hjzWRO3vX/VxnYEA6f0bpqHq1tZi6lzix5CTUN5McpDg ++QnjenSJNrNjS1zEF8WeY9iLEuDI/M/iUW4y9R6s3WpgQhPDXpSvd2g3gMGRUYhxQ ++Xna8auiJeYFq0oNaOxvJj+VeOfJ3ZMJttd+Y7gTOYZcbg3SdRb/kdxYki0RMD2hF ++4ZvjJ6CTfwKBwQDiMqiZFTJGQwYqp4vWEmAW+I4r4xkUpWatoI2Fk5eI5T9+1PLX ++uYXsho56NxEU1UrOg4Cb/p+TcBc8PErkGqR0BkpxDMOInTOXSrQe6lxIBoECVXc3 ++HTbrmiay0a5y5GfCgxPKqIJhfcToAceoVjovv0y7S4yoxGZKuUEe7E8JY2iqRNAO ++yOvKCCICv/hcN235E44RF+2/rDlOltagNej5tY6rIFkaDdgOF4bD7f9O5eEni1Bg ++litfoesDtQP/3rECgcEAkQfvQ7D6tIPmbqsbJBfCr6fmoqZllT4FIJN84b50+OL0 ++mTGsfjdqC4tdhx3sdu7/VPbaIqm5NmX10bowWgWSY7MbVME4yQPyqSwC5NbIonEC ++d6N0mzoLR0kQ+Ai4u+2g82gicgAq2oj1uSNi3WZi48jQjHYFulCbo246o1NgeFFK ++77WshYe2R1ioQfQDOU1URKCR0uTaMHClgfu112yiGd12JAD+aF3TM0kxDXz+sXI5 ++SKy311DFxECZeXRLpcC3AoHBAJkNMJWTyPYbeVu+CTQkec8Uun233EkXa2kUNZc/ ++5DuXDaK+A3DMgYRufTKSPpDHGaCZ1SYPInX1Uoe2dgVjWssRL2uitR4ENabDoAOA ++ICVYXYYNagqQu5wwirF0QeaMXo1fjhuuHQh8GsMdXZvYEaAITZ9/NG5x/oY08+8H ++kr78SMBOPy3XQn964uKG+e3JwpOG14GKABdAlrHKFXNWchu/6dgcYXB87mrC/GhO ++zNwzC+QhFTZoOomFoqMgFWujng== + -----END PRIVATE KEY----- +diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py +index 1e0f14eb3a..c2cc009b9f 100644 +--- a/Lib/test/support/__init__.py ++++ b/Lib/test/support/__init__.py +@@ -1151,6 +1151,9 @@ def transient_internet(resource_name, timeout=30.0, errnos=()): + ('EHOSTUNREACH', 113), + ('ENETUNREACH', 101), + ('ETIMEDOUT', 110), ++ # socket.create_connection() fails randomly with ++ # EADDRNOTAVAIL on Travis CI. ++ ('EADDRNOTAVAIL', 99), + ] + default_gai_errnos = [ + ('EAI_AGAIN', -3), +@@ -1671,6 +1674,14 @@ def run_doctest(module, verbosity=None): + #======================================================================= + # Threading support to prevent reporting refleaks when running regrtest.py -R + ++# Flag used by saved_test_environment of test.libregrtest.save_env, ++# to check if a test modified the environment. The flag should be set to False ++# before running a new test. ++# ++# For example, threading_cleanup() sets the flag is the function fails ++# to cleanup threads. ++environment_altered = False ++ + # NOTE: we use thread._count() rather than threading.enumerate() (or the + # moral equivalent thereof) because a threading.Thread object is still alive + # until its __bootstrap() method has returned, even after it has been +@@ -1714,6 +1725,43 @@ def reap_threads(func): + threading_cleanup(*key) + return decorator + ++ ++@contextlib.contextmanager ++def wait_threads_exit(timeout=60.0): ++ """ ++ bpo-31234: Context manager to wait until all threads created in the with ++ statement exit. ++ ++ Use thread.count() to check if threads exited. Indirectly, wait until ++ threads exit the internal t_bootstrap() C function of the thread module. ++ ++ threading_setup() and threading_cleanup() are designed to emit a warning ++ if a test leaves running threads in the background. This context manager ++ is designed to cleanup threads started by the thread.start_new_thread() ++ which doesn't allow to wait for thread exit, whereas thread.Thread has a ++ join() method. ++ """ ++ old_count = thread._count() ++ try: ++ yield ++ finally: ++ start_time = time.time() ++ deadline = start_time + timeout ++ while True: ++ count = thread._count() ++ if count <= old_count: ++ break ++ if time.time() > deadline: ++ dt = time.time() - start_time ++ msg = ("wait_threads() failed to cleanup %s " ++ "threads after %.1f seconds " ++ "(count: %s, old count: %s)" ++ % (count - old_count, dt, count, old_count)) ++ raise AssertionError(msg) ++ time.sleep(0.010) ++ gc_collect() ++ ++ + def reap_children(): + """Use this function at the end of test_main() whenever sub-processes + are started. This will help ensure that no extra children (zombies) +@@ -2017,6 +2065,66 @@ def _crash_python(): + _testcapi._read_null() + + ++def fd_count(): ++ """Count the number of open file descriptors. ++ """ ++ if sys.platform.startswith(('linux', 'freebsd')): ++ try: ++ names = os.listdir("/proc/self/fd") ++ # Substract one because listdir() opens internally a file ++ # descriptor to list the content of the /proc/self/fd/ directory. ++ return len(names) - 1 ++ except OSError as exc: ++ if exc.errno != errno.ENOENT: ++ raise ++ ++ MAXFD = 256 ++ if hasattr(os, 'sysconf'): ++ try: ++ MAXFD = os.sysconf("SC_OPEN_MAX") ++ except OSError: ++ pass ++ ++ old_modes = None ++ if sys.platform == 'win32': ++ # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process ++ # on invalid file descriptor if Python is compiled in debug mode ++ try: ++ import msvcrt ++ msvcrt.CrtSetReportMode ++ except (AttributeError, ImportError): ++ # no msvcrt or a release build ++ pass ++ else: ++ old_modes = {} ++ for report_type in (msvcrt.CRT_WARN, ++ msvcrt.CRT_ERROR, ++ msvcrt.CRT_ASSERT): ++ old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, 0) ++ ++ try: ++ count = 0 ++ for fd in range(MAXFD): ++ try: ++ # Prefer dup() over fstat(). fstat() can require input/output ++ # whereas dup() doesn't. ++ fd2 = os.dup(fd) ++ except OSError as e: ++ if e.errno != errno.EBADF: ++ raise ++ else: ++ os.close(fd2) ++ count += 1 ++ finally: ++ if old_modes is not None: ++ for report_type in (msvcrt.CRT_WARN, ++ msvcrt.CRT_ERROR, ++ msvcrt.CRT_ASSERT): ++ msvcrt.CrtSetReportMode(report_type, old_modes[report_type]) ++ ++ return count ++ ++ + class SaveSignals: + """ + Save an restore signal handlers. +diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py +index 83f6f27d78..f39565ab12 100644 +--- a/Lib/test/test_argparse.py ++++ b/Lib/test/test_argparse.py +@@ -4652,7 +4652,7 @@ class TestAddArgumentMetavar(TestCase): + self.do_test_exception(nargs=None, metavar=tuple()) + + def test_nargs_None_metavar_length1(self): +- self.do_test_no_exception(nargs=None, metavar=("1")) ++ self.do_test_no_exception(nargs=None, metavar=("1",)) + + def test_nargs_None_metavar_length2(self): + self.do_test_exception(nargs=None, metavar=("1", "2")) +@@ -4669,7 +4669,7 @@ class TestAddArgumentMetavar(TestCase): + self.do_test_exception(nargs="?", metavar=tuple()) + + def test_nargs_optional_metavar_length1(self): +- self.do_test_no_exception(nargs="?", metavar=("1")) ++ self.do_test_no_exception(nargs="?", metavar=("1",)) + + def test_nargs_optional_metavar_length2(self): + self.do_test_exception(nargs="?", metavar=("1", "2")) +@@ -4686,7 +4686,7 @@ class TestAddArgumentMetavar(TestCase): + self.do_test_exception(nargs="*", metavar=tuple()) + + def test_nargs_zeroormore_metavar_length1(self): +- self.do_test_no_exception(nargs="*", metavar=("1")) ++ self.do_test_exception(nargs="*", metavar=("1",)) + + def test_nargs_zeroormore_metavar_length2(self): + self.do_test_no_exception(nargs="*", metavar=("1", "2")) +@@ -4703,7 +4703,7 @@ class TestAddArgumentMetavar(TestCase): + self.do_test_exception(nargs="+", metavar=tuple()) + + def test_nargs_oneormore_metavar_length1(self): +- self.do_test_no_exception(nargs="+", metavar=("1")) ++ self.do_test_exception(nargs="+", metavar=("1",)) + + def test_nargs_oneormore_metavar_length2(self): + self.do_test_no_exception(nargs="+", metavar=("1", "2")) +@@ -4720,7 +4720,7 @@ class TestAddArgumentMetavar(TestCase): + self.do_test_no_exception(nargs="...", metavar=tuple()) + + def test_nargs_remainder_metavar_length1(self): +- self.do_test_no_exception(nargs="...", metavar=("1")) ++ self.do_test_no_exception(nargs="...", metavar=("1",)) + + def test_nargs_remainder_metavar_length2(self): + self.do_test_no_exception(nargs="...", metavar=("1", "2")) +@@ -4737,7 +4737,7 @@ class TestAddArgumentMetavar(TestCase): + self.do_test_exception(nargs="A...", metavar=tuple()) + + def test_nargs_parser_metavar_length1(self): +- self.do_test_no_exception(nargs="A...", metavar=("1")) ++ self.do_test_no_exception(nargs="A...", metavar=("1",)) + + def test_nargs_parser_metavar_length2(self): + self.do_test_exception(nargs="A...", metavar=("1", "2")) +@@ -4754,7 +4754,7 @@ class TestAddArgumentMetavar(TestCase): + self.do_test_exception(nargs=1, metavar=tuple()) + + def test_nargs_1_metavar_length1(self): +- self.do_test_no_exception(nargs=1, metavar=("1")) ++ self.do_test_no_exception(nargs=1, metavar=("1",)) + + def test_nargs_1_metavar_length2(self): + self.do_test_exception(nargs=1, metavar=("1", "2")) +@@ -4771,7 +4771,7 @@ class TestAddArgumentMetavar(TestCase): + self.do_test_exception(nargs=2, metavar=tuple()) + + def test_nargs_2_metavar_length1(self): +- self.do_test_no_exception(nargs=2, metavar=("1")) ++ self.do_test_exception(nargs=2, metavar=("1",)) + + def test_nargs_2_metavar_length2(self): + self.do_test_no_exception(nargs=2, metavar=("1", "2")) +@@ -4788,7 +4788,7 @@ class TestAddArgumentMetavar(TestCase): + self.do_test_exception(nargs=3, metavar=tuple()) + + def test_nargs_3_metavar_length1(self): +- self.do_test_no_exception(nargs=3, metavar=("1")) ++ self.do_test_exception(nargs=3, metavar=("1",)) + + def test_nargs_3_metavar_length2(self): + self.do_test_exception(nargs=3, metavar=("1", "2")) +@@ -4815,6 +4815,30 @@ class TestImportStar(TestCase): + ] + self.assertEqual(sorted(items), sorted(argparse.__all__)) + ++ ++class TestWrappingMetavar(TestCase): ++ ++ def setUp(self): ++ self.parser = ErrorRaisingArgumentParser( ++ 'this_is_spammy_prog_with_a_long_name_sorry_about_the_name' ++ ) ++ # this metavar was triggering library assertion errors due to usage ++ # message formatting incorrectly splitting on the ] chars within ++ metavar = '' ++ self.parser.add_argument('--proxy', metavar=metavar) ++ ++ def test_help_with_metavar(self): ++ help_text = self.parser.format_help() ++ self.assertEqual(help_text, textwrap.dedent('''\ ++ usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name ++ [-h] [--proxy ] ++ ++ optional arguments: ++ -h, --help show this help message and exit ++ --proxy ++ ''')) ++ ++ + def test_main(): + # silence warnings about version argument - these are expected + with test_support.check_warnings( +diff --git a/Lib/test/test_asyncore.py b/Lib/test/test_asyncore.py +index 693d67cd8a..4b347a3a6d 100644 +--- a/Lib/test/test_asyncore.py ++++ b/Lib/test/test_asyncore.py +@@ -727,19 +727,20 @@ class BaseTestAPI(unittest.TestCase): + server = TCPServer() + t = threading.Thread(target=lambda: asyncore.loop(timeout=0.1, count=500)) + t.start() +- self.addCleanup(t.join) +- +- for x in xrange(20): +- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +- s.settimeout(.2) +- s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, +- struct.pack('ii', 1, 0)) +- try: +- s.connect(server.address) +- except socket.error: +- pass +- finally: +- s.close() ++ try: ++ for x in xrange(20): ++ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ++ s.settimeout(.2) ++ s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, ++ struct.pack('ii', 1, 0)) ++ try: ++ s.connect(server.address) ++ except socket.error: ++ pass ++ finally: ++ s.close() ++ finally: ++ t.join() + + + class TestAPI_UseSelect(BaseTestAPI): +diff --git a/Lib/test/test_bdb.py b/Lib/test/test_bdb.py +new file mode 100644 +index 0000000000..4fb7c79cdc +--- /dev/null ++++ b/Lib/test/test_bdb.py +@@ -0,0 +1,1034 @@ ++""" Test the bdb module. ++ ++ A test defines a list of tuples that may be seen as paired tuples, each ++ pair being defined by 'expect_tuple, set_tuple' as follows: ++ ++ ([event, [lineno[, co_name[, eargs]]]]), (set_type, [sargs]) ++ ++ * 'expect_tuple' describes the expected current state of the Bdb instance. ++ It may be the empty tuple and no check is done in that case. ++ * 'set_tuple' defines the set_*() method to be invoked when the Bdb ++ instance reaches this state. ++ ++ Example of an 'expect_tuple, set_tuple' pair: ++ ++ ('line', 2, 'tfunc_main'), ('step', ) ++ ++ Definitions of the members of the 'expect_tuple': ++ event: ++ Name of the trace event. The set methods that do not give back ++ control to the tracer [1] do not trigger a tracer event and in ++ that case the next 'event' may be 'None' by convention, its value ++ is not checked. ++ [1] Methods that trigger a trace event are set_step(), set_next(), ++ set_return(), set_until() and set_continue(). ++ lineno: ++ Line number. Line numbers are relative to the start of the ++ function when tracing a function in the test_bdb module (i.e. this ++ module). ++ co_name: ++ Name of the function being currently traced. ++ eargs: ++ A tuple: ++ * On an 'exception' event the tuple holds a class object, the ++ current exception must be an instance of this class. ++ * On a 'line' event, the tuple holds a dictionary and a list. The ++ dictionary maps each breakpoint number that has been hit on this ++ line to its hits count. The list holds the list of breakpoint ++ number temporaries that are being deleted. ++ ++ Definitions of the members of the 'set_tuple': ++ set_type: ++ The type of the set method to be invoked. This may ++ be the type of one of the Bdb set methods: 'step', 'next', ++ 'until', 'return', 'continue', 'break', 'quit', or the type of one ++ of the set methods added by test_bdb.Bdb: 'ignore', 'enable', ++ 'disable', 'clear', 'up', 'down'. ++ sargs: ++ The arguments of the set method if any, packed in a tuple. ++""" ++ ++from __future__ import absolute_import ++from __future__ import print_function ++ ++import bdb as _bdb ++import sys ++import os ++import unittest ++import textwrap ++import importlib ++import linecache ++from contextlib import contextmanager ++from itertools import islice, repeat ++import test.support ++ ++class BdbException(Exception): pass ++class BdbError(BdbException): """Error raised by the Bdb instance.""" ++class BdbSyntaxError(BdbException): """Syntax error in the test case.""" ++class BdbNotExpectedError(BdbException): """Unexpected result.""" ++ ++# When 'dry_run' is set to true, expect tuples are ignored and the actual ++# state of the tracer is printed after running each set_*() method of the test ++# case. The full list of breakpoints and their attributes is also printed ++# after each 'line' event where a breakpoint has been hit. ++dry_run = 0 ++ ++__file__ = os.path.splitext(__file__)[0] + '.py' ++ ++def reset_Breakpoint(): ++ _bdb.Breakpoint.next = 1 ++ _bdb.Breakpoint.bplist = {} ++ _bdb.Breakpoint.bpbynumber = [None] ++ ++def info_breakpoints(): ++ bp_list = [bp for bp in _bdb.Breakpoint.bpbynumber if bp] ++ if not bp_list: ++ return '' ++ ++ header_added = False ++ for bp in bp_list: ++ if not header_added: ++ info = 'BpNum Temp Enb Hits Ignore Where\n' ++ header_added = True ++ ++ disp = 'yes ' if bp.temporary else 'no ' ++ enab = 'yes' if bp.enabled else 'no ' ++ info += ('%-5d %s %s %-4d %-6d at %s:%d' % ++ (bp.number, disp, enab, bp.hits, bp.ignore, ++ os.path.basename(bp.file), bp.line)) ++ if bp.cond: ++ info += '\n\tstop only if %s' % (bp.cond,) ++ info += '\n' ++ return info ++ ++class Bdb(_bdb.Bdb, object): ++ """Extend Bdb to enhance test coverage.""" ++ ++ def trace_dispatch(self, frame, event, arg): ++ self.currentbp = None ++ return super(Bdb, self).trace_dispatch(frame, event, arg) ++ ++ def set_break(self, filename, lineno, temporary=False, cond=None, ++ funcname=None): ++ if isinstance(funcname, str): ++ if filename == __file__: ++ globals_ = globals() ++ else: ++ module = importlib.import_module(filename[:-3]) ++ globals_ = module.__dict__ ++ func = eval(funcname, globals_) ++ code = func.__code__ ++ filename = code.co_filename ++ lineno = code.co_firstlineno ++ funcname = code.co_name ++ ++ res = super(Bdb, self).set_break(filename, lineno, ++ temporary=temporary, cond=cond, funcname=funcname) ++ if isinstance(res, str): ++ raise BdbError(res) ++ return res ++ ++ # Back port of get_bpbynumber() from bdb.Bdb in Python 3. ++ def get_bpbynumber(self, arg): ++ """Return a breakpoint by its index in Breakpoint.bybpnumber. ++ ++ For invalid arg values or if the breakpoint doesn't exist, ++ raise a ValueError. ++ """ ++ if not arg: ++ raise ValueError('Breakpoint number expected') ++ try: ++ number = int(arg) ++ except ValueError: ++ raise ValueError('Non-numeric breakpoint number %s' % arg) ++ try: ++ bp = _bdb.Breakpoint.bpbynumber[number] ++ except IndexError: ++ raise ValueError('Breakpoint number %d out of range' % number) ++ if bp is None: ++ raise ValueError('Breakpoint %d already deleted' % number) ++ return bp ++ ++ def get_stack(self, f, t): ++ self.stack, self.index = super(Bdb, self).get_stack(f, t) ++ self.frame = self.stack[self.index][0] ++ return self.stack, self.index ++ ++ def set_ignore(self, bpnum): ++ """Increment the ignore count of Breakpoint number 'bpnum'.""" ++ bp = self.get_bpbynumber(bpnum) ++ bp.ignore += 1 ++ ++ def set_enable(self, bpnum): ++ bp = self.get_bpbynumber(bpnum) ++ bp.enabled = True ++ ++ def set_disable(self, bpnum): ++ bp = self.get_bpbynumber(bpnum) ++ bp.enabled = False ++ ++ def set_clear(self, fname, lineno): ++ err = self.clear_break(fname, lineno) ++ if err: ++ raise BdbError(err) ++ ++ def set_up(self): ++ """Move up in the frame stack.""" ++ if not self.index: ++ raise BdbError('Oldest frame') ++ self.index -= 1 ++ self.frame = self.stack[self.index][0] ++ ++ def set_down(self): ++ """Move down in the frame stack.""" ++ if self.index + 1 == len(self.stack): ++ raise BdbError('Newest frame') ++ self.index += 1 ++ self.frame = self.stack[self.index][0] ++ ++class Tracer(Bdb): ++ """A tracer for testing the bdb module.""" ++ ++ def __init__(self, expect_set, skip=None, dry_run=False, test_case=None): ++ super(Tracer, self).__init__(skip=skip) ++ self.expect_set = expect_set ++ self.dry_run = dry_run ++ self.header = ('Dry-run results for %s:' % test_case if ++ test_case is not None else None) ++ self.init_test() ++ ++ def init_test(self): ++ self.cur_except = None ++ self.expect_set_no = 0 ++ self.breakpoint_hits = None ++ self.expected_list = list(islice(self.expect_set, 0, None, 2)) ++ self.set_list = list(islice(self.expect_set, 1, None, 2)) ++ ++ def trace_dispatch(self, frame, event, arg): ++ # On an 'exception' event, call_exc_trace() in Python/ceval.c discards ++ # a BdbException raised by the Tracer instance, so we raise it on the ++ # next trace_dispatch() call that occurs unless the set_quit() or ++ # set_continue() method has been invoked on the 'exception' event. ++ if self.cur_except is not None: ++ raise self.cur_except ++ ++ if event == 'exception': ++ try: ++ res = super(Tracer, self).trace_dispatch(frame, event, arg) ++ return res ++ except BdbException as e: ++ self.cur_except = e ++ return self.trace_dispatch ++ else: ++ return super(Tracer, self).trace_dispatch(frame, event, arg) ++ ++ def user_call(self, frame, argument_list): ++ # Adopt the same behavior as pdb and, as a side effect, skip also the ++ # first 'call' event when the Tracer is started with Tracer.runcall() ++ # which may be possibly considered as a bug. ++ if not self.stop_here(frame): ++ return ++ self.process_event('call', frame, argument_list) ++ self.next_set_method() ++ ++ def user_line(self, frame): ++ self.process_event('line', frame) ++ ++ if self.dry_run and self.breakpoint_hits: ++ info = info_breakpoints().strip('\n') ++ # Indent each line. ++ for line in info.split('\n'): ++ print(' ' + line) ++ self.delete_temporaries() ++ self.breakpoint_hits = None ++ ++ self.next_set_method() ++ ++ def user_return(self, frame, return_value): ++ self.process_event('return', frame, return_value) ++ self.next_set_method() ++ ++ def user_exception(self, frame, exc_info): ++ self.exc_info = exc_info ++ self.process_event('exception', frame) ++ self.next_set_method() ++ ++ def do_clear(self, arg): ++ # The temporary breakpoints are deleted in user_line(). ++ bp_list = [self.currentbp] ++ self.breakpoint_hits = (bp_list, bp_list) ++ ++ def delete_temporaries(self): ++ if self.breakpoint_hits: ++ for n in self.breakpoint_hits[1]: ++ self.clear_bpbynumber(n) ++ ++ def pop_next(self): ++ self.expect_set_no += 1 ++ try: ++ self.expect = self.expected_list.pop(0) ++ except IndexError: ++ raise BdbNotExpectedError( ++ 'expect_set list exhausted, cannot pop item %d' % ++ self.expect_set_no) ++ self.set_tuple = self.set_list.pop(0) ++ ++ def process_event(self, event, frame, *args): ++ # Call get_stack() to enable walking the stack with set_up() and ++ # set_down(). ++ tb = None ++ if event == 'exception': ++ tb = self.exc_info[2] ++ self.get_stack(frame, tb) ++ ++ # A breakpoint has been hit and it is not a temporary. ++ if self.currentbp is not None and not self.breakpoint_hits: ++ bp_list = [self.currentbp] ++ self.breakpoint_hits = (bp_list, []) ++ ++ # Pop next event. ++ self.event= event ++ self.pop_next() ++ if self.dry_run: ++ self.print_state(self.header) ++ return ++ ++ # Validate the expected results. ++ if self.expect: ++ self.check_equal(self.expect[0], event, 'Wrong event type') ++ self.check_lno_name() ++ ++ if event in ('call', 'return'): ++ self.check_expect_max_size(3) ++ elif len(self.expect) > 3: ++ if event == 'line': ++ bps, temporaries = self.expect[3] ++ bpnums = sorted(bps.keys()) ++ if not self.breakpoint_hits: ++ self.raise_not_expected( ++ 'No breakpoints hit at expect_set item %d' % ++ self.expect_set_no) ++ self.check_equal(bpnums, self.breakpoint_hits[0], ++ 'Breakpoint numbers do not match') ++ self.check_equal([bps[n] for n in bpnums], ++ [self.get_bpbynumber(n).hits for ++ n in self.breakpoint_hits[0]], ++ 'Wrong breakpoint hit count') ++ self.check_equal(sorted(temporaries), self.breakpoint_hits[1], ++ 'Wrong temporary breakpoints') ++ ++ elif event == 'exception': ++ if not isinstance(self.exc_info[1], self.expect[3]): ++ self.raise_not_expected( ++ "Wrong exception at expect_set item %d, got '%s'" % ++ (self.expect_set_no, self.exc_info)) ++ ++ def check_equal(self, expected, result, msg): ++ if expected == result: ++ return ++ self.raise_not_expected("%s at expect_set item %d, got '%s'" % ++ (msg, self.expect_set_no, result)) ++ ++ def check_lno_name(self): ++ """Check the line number and function co_name.""" ++ s = len(self.expect) ++ if s > 1: ++ lineno = self.lno_abs2rel() ++ self.check_equal(self.expect[1], lineno, 'Wrong line number') ++ if s > 2: ++ self.check_equal(self.expect[2], self.frame.f_code.co_name, ++ 'Wrong function name') ++ ++ def check_expect_max_size(self, size): ++ if len(self.expect) > size: ++ raise BdbSyntaxError('Invalid size of the %s expect tuple: %s' % ++ (self.event, self.expect)) ++ ++ def lno_abs2rel(self): ++ fname = self.canonic(self.frame.f_code.co_filename) ++ lineno = self.frame.f_lineno ++ return ((lineno - self.frame.f_code.co_firstlineno + 1) ++ if fname == self.canonic(__file__) else lineno) ++ ++ def lno_rel2abs(self, fname, lineno): ++ return (self.frame.f_code.co_firstlineno + lineno - 1 ++ if (lineno and self.canonic(fname) == self.canonic(__file__)) ++ else lineno) ++ ++ def get_state(self): ++ lineno = self.lno_abs2rel() ++ co_name = self.frame.f_code.co_name ++ state = "('%s', %d, '%s'" % (self.event, lineno, co_name) ++ if self.breakpoint_hits: ++ bps = '{' ++ for n in self.breakpoint_hits[0]: ++ if bps != '{': ++ bps += ', ' ++ bps += '%s: %s' % (n, self.get_bpbynumber(n).hits) ++ bps += '}' ++ bps = '(' + bps + ', ' + str(self.breakpoint_hits[1]) + ')' ++ state += ', ' + bps ++ elif self.event == 'exception': ++ state += ', ' + self.exc_info[0].__name__ ++ state += '), ' ++ return state.ljust(32) + str(self.set_tuple) + ',' ++ ++ def print_state(self, header=None): ++ if header is not None and self.expect_set_no == 1: ++ print() ++ print(header) ++ print('%d: %s' % (self.expect_set_no, self.get_state())) ++ ++ def raise_not_expected(self, msg): ++ msg += '\n' ++ msg += ' Expected: %s\n' % str(self.expect) ++ msg += ' Got: ' + self.get_state() ++ raise BdbNotExpectedError(msg) ++ ++ def next_set_method(self): ++ set_type = self.set_tuple[0] ++ args = self.set_tuple[1] if len(self.set_tuple) == 2 else None ++ set_method = getattr(self, 'set_' + set_type) ++ ++ # The following set methods give back control to the tracer. ++ if set_type in ('step', 'continue', 'quit'): ++ set_method() ++ return ++ elif set_type in ('next', 'return'): ++ set_method(self.frame) ++ return ++ elif set_type == 'until': ++ set_method(self.frame) ++ return ++ ++ # The following set methods do not give back control to the tracer and ++ # next_set_method() is called recursively. ++ if (args and set_type in ('break', 'clear', 'ignore', 'enable', ++ 'disable')) or set_type in ('up', 'down'): ++ if set_type in ('break', 'clear'): ++ fname = args[0] ++ lineno = args[1] ++ lineno = self.lno_rel2abs(fname, lineno) ++ args = [fname, lineno] + list(args[2:]) ++ set_method(*args) ++ elif set_type in ('ignore', 'enable', 'disable'): ++ set_method(*args) ++ elif set_type in ('up', 'down'): ++ set_method() ++ ++ # Process the next expect_set item. ++ # It is not expected that a test may reach the recursion limit. ++ self.event= None ++ self.pop_next() ++ if self.dry_run: ++ self.print_state() ++ else: ++ if self.expect: ++ self.check_lno_name() ++ self.check_expect_max_size(3) ++ self.next_set_method() ++ else: ++ raise BdbSyntaxError('"%s" is an invalid set_tuple' % ++ self.set_tuple) ++ ++class TracerRun(): ++ """Provide a context for running a Tracer instance with a test case.""" ++ ++ def __init__(self, test_case, skip=None): ++ self.test_case = test_case ++ self.dry_run = test_case.dry_run ++ self.tracer = Tracer(test_case.expect_set, skip=skip, ++ dry_run=self.dry_run, test_case=test_case.id()) ++ ++ def __enter__(self): ++ # test_pdb does not reset Breakpoint class attributes on exit :-( ++ reset_Breakpoint() ++ return self.tracer ++ ++ def __exit__(self, type_=None, value=None, traceback=None): ++ reset_Breakpoint() ++ sys.settrace(None) ++ ++ not_empty = '' ++ if self.tracer.set_list: ++ not_empty += 'All paired tuples have not been processed, ' ++ not_empty += ('the last one was number %d' % ++ self.tracer.expect_set_no) ++ ++ # Make a BdbNotExpectedError a unittest failure. ++ if type_ is not None and issubclass(BdbNotExpectedError, type_): ++ if isinstance(value, BaseException) and value.args: ++ err_msg = value.args[0] ++ if not_empty: ++ err_msg += '\n' + not_empty ++ if self.dry_run: ++ print(err_msg) ++ return True ++ else: ++ self.test_case.fail(err_msg) ++ else: ++ assert False, 'BdbNotExpectedError with empty args' ++ ++ if not_empty: ++ if self.dry_run: ++ print(not_empty) ++ else: ++ self.test_case.fail(not_empty) ++ ++def run_test(modules, set_list, skip=None): ++ """Run a test and print the dry-run results. ++ ++ 'modules': A dictionary mapping module names to their source code as a ++ string. The dictionary MUST include one module named ++ 'test_module' with a main() function. ++ 'set_list': A list of set_type tuples to be run on the module. ++ ++ For example, running the following script outputs the following results: ++ ++ ***************************** SCRIPT ******************************** ++ ++ from test.test_bdb import run_test, break_in_func ++ ++ code = ''' ++ def func(): ++ lno = 3 ++ ++ def main(): ++ func() ++ lno = 7 ++ ''' ++ ++ set_list = [ ++ break_in_func('func', 'test_module.py'), ++ ('continue', ), ++ ('step', ), ++ ('step', ), ++ ('step', ), ++ ('quit', ), ++ ] ++ ++ modules = { 'test_module': code } ++ run_test(modules, set_list) ++ ++ **************************** results ******************************** ++ ++ 1: ('line', 2, 'tfunc_import'), ('next',), ++ 2: ('line', 3, 'tfunc_import'), ('step',), ++ 3: ('call', 5, 'main'), ('break', ('test_module.py', None, False, None, 'func')), ++ 4: ('None', 5, 'main'), ('continue',), ++ 5: ('line', 3, 'func', ({1: 1}, [])), ('step',), ++ BpNum Temp Enb Hits Ignore Where ++ 1 no yes 1 0 at test_module.py:2 ++ 6: ('return', 3, 'func'), ('step',), ++ 7: ('line', 7, 'main'), ('step',), ++ 8: ('return', 7, 'main'), ('quit',), ++ ++ ************************************************************************* ++ ++ """ ++ def gen(a, b): ++ try: ++ while 1: ++ x = next(a) ++ y = next(b) ++ yield x ++ yield y ++ except StopIteration: ++ return ++ ++ # Step over the import statement in tfunc_import using 'next' and step ++ # into main() in test_module. ++ sl = [('next', ), ('step', )] ++ sl.extend(set_list) ++ ++ test = BaseTestCase() ++ test.dry_run = True ++ test.id = lambda : None ++ test.expect_set = list(gen(repeat(()), iter(sl))) ++ with create_modules(modules): ++ sys.path.append(os.getcwd()) ++ with TracerRun(test, skip=skip) as tracer: ++ tracer.runcall(tfunc_import) ++ ++@contextmanager ++def create_modules(modules): ++ with test.support.temp_cwd(): ++ try: ++ sys.path.insert(0, os.getcwd()) ++ for m in modules: ++ fname = m + '.py' ++ with open(fname, 'w') as f: ++ f.write(textwrap.dedent(modules[m])) ++ linecache.checkcache(fname) ++ yield ++ finally: ++ sys.path.pop(0) ++ for m in modules: ++ test.support.forget(m) ++ ++def break_in_func(funcname, fname=__file__, temporary=False, cond=None): ++ return 'break', (fname, None, temporary, cond, funcname) ++ ++TEST_MODULE = 'test_module' ++TEST_MODULE_FNAME = TEST_MODULE + '.py' ++def tfunc_import(): ++ import test_module ++ test_module.main() ++ ++def tfunc_main(): ++ lno = 2 ++ tfunc_first() ++ tfunc_second() ++ lno = 5 ++ lno = 6 ++ lno = 7 ++ ++def tfunc_first(): ++ lno = 2 ++ lno = 3 ++ lno = 4 ++ ++def tfunc_second(): ++ lno = 2 ++ ++class BaseTestCase(unittest.TestCase): ++ """Base class for all tests.""" ++ dry_run = dry_run ++ ++class StateTestCase(BaseTestCase): ++ """Test the step, next, return, until and quit 'set_' methods.""" ++ ++ def test_step(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('step', ), ++ ('line', 2, 'tfunc_first'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_step_on_last_statement(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('break', (__file__, 3)), ++ ('None', 1, 'tfunc_first'), ('continue', ), ++ ('line', 3, 'tfunc_first', ({1:1}, [])), ('step', ), ++ ('line', 4, 'tfunc_first'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_next_on_last_statement(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('break', (__file__, 3)), ++ ('None', 1, 'tfunc_first'), ('continue', ), ++ ('line', 3, 'tfunc_first', ({1:1}, [])), ('next', ), ++ ('line', 4, 'tfunc_first'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_next(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('next', ), ++ ('line', 4, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_second'), ('step', ), ++ ('line', 2, 'tfunc_second'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_next_over_import(self): ++ code = """ ++ def main(): ++ lno = 3 ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ('next', ), ++ ('line', 3, 'tfunc_import'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_import) ++ ++ def test_next_on_plain_statement(self): ++ # Check that set_next() is equivalent to set_step() on a plain ++ # statement. ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('next', ), ++ ('line', 2, 'tfunc_first'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_next_in_caller_frame(self): ++ # Check that set_next() in the caller frame causes the tracer ++ # to stop next in the caller frame. ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('up', ), ++ ('None', 3, 'tfunc_main'), ('next', ), ++ ('line', 4, 'tfunc_main'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_return(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('step', ), ++ ('line', 2, 'tfunc_first'), ('return', ), ++ ('return', 4, 'tfunc_first'), ('step', ), ++ ('line', 4, 'tfunc_main'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_return_in_caller_frame(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('up', ), ++ ('None', 3, 'tfunc_main'), ('return', ), ++ ('return', 7, 'tfunc_main'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_until(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('step', ), ++ ('line', 2, 'tfunc_first'), ('until', ), ++ ('line', 3, 'tfunc_first'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_until_in_caller_frame(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('up', ), ++ ('None', 3, 'tfunc_main'), ('until', ), ++ ('line', 4, 'tfunc_main'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++ def test_skip(self): ++ # Check that tracing is skipped over the import statement in ++ # 'tfunc_import()'. ++ code = """ ++ def main(): ++ lno = 3 ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ('step', ), ++ ('line', 3, 'tfunc_import'), ('quit', ), ++ ] ++ skip = ('importlib*', TEST_MODULE) ++ with TracerRun(self, skip=skip) as tracer: ++ tracer.runcall(tfunc_import) ++ ++ def test_down(self): ++ # Check that set_down() raises BdbError at the newest frame. ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('down', ), ++ ] ++ with TracerRun(self) as tracer: ++ self.assertRaises(BdbError, tracer.runcall, tfunc_main) ++ ++ def test_up(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_main'), ('step', ), ++ ('line', 3, 'tfunc_main'), ('step', ), ++ ('call', 1, 'tfunc_first'), ('up', ), ++ ('None', 3, 'tfunc_main'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_main) ++ ++class BreakpointTestCase(BaseTestCase): ++ """Test the breakpoint set method.""" ++ ++ def test_bp_on_non_existent_module(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ('break', ('/non/existent/module.py', 1)) ++ ] ++ with TracerRun(self) as tracer: ++ self.assertRaises(BdbError, tracer.runcall, tfunc_import) ++ ++ def test_bp_after_last_statement(self): ++ code = """ ++ def main(): ++ lno = 3 ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ('break', (TEST_MODULE_FNAME, 4)) ++ ] ++ with TracerRun(self) as tracer: ++ self.assertRaises(BdbError, tracer.runcall, tfunc_import) ++ ++ def test_temporary_bp(self): ++ code = """ ++ def func(): ++ lno = 3 ++ ++ def main(): ++ for i in range(2): ++ func() ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ++ break_in_func('func', TEST_MODULE_FNAME, True), ++ ('None', 2, 'tfunc_import'), ++ break_in_func('func', TEST_MODULE_FNAME, True), ++ ('None', 2, 'tfunc_import'), ('continue', ), ++ ('line', 3, 'func', ({1:1}, [1])), ('continue', ), ++ ('line', 3, 'func', ({2:1}, [2])), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_import) ++ ++ def test_disabled_temporary_bp(self): ++ code = """ ++ def func(): ++ lno = 3 ++ ++ def main(): ++ for i in range(3): ++ func() ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ++ break_in_func('func', TEST_MODULE_FNAME), ++ ('None', 2, 'tfunc_import'), ++ break_in_func('func', TEST_MODULE_FNAME, True), ++ ('None', 2, 'tfunc_import'), ('disable', (2, )), ++ ('None', 2, 'tfunc_import'), ('continue', ), ++ ('line', 3, 'func', ({1:1}, [])), ('enable', (2, )), ++ ('None', 3, 'func'), ('disable', (1, )), ++ ('None', 3, 'func'), ('continue', ), ++ ('line', 3, 'func', ({2:1}, [2])), ('enable', (1, )), ++ ('None', 3, 'func'), ('continue', ), ++ ('line', 3, 'func', ({1:2}, [])), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_import) ++ ++ def test_bp_condition(self): ++ code = """ ++ def func(a): ++ lno = 3 ++ ++ def main(): ++ for i in range(3): ++ func(i) ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ++ break_in_func('func', TEST_MODULE_FNAME, False, 'a == 2'), ++ ('None', 2, 'tfunc_import'), ('continue', ), ++ ('line', 3, 'func', ({1:3}, [])), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_import) ++ ++ def test_bp_exception_on_condition_evaluation(self): ++ code = """ ++ def func(a): ++ lno = 3 ++ ++ def main(): ++ func(0) ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ++ break_in_func('func', TEST_MODULE_FNAME, False, '1 / 0'), ++ ('None', 2, 'tfunc_import'), ('continue', ), ++ ('line', 3, 'func', ({1:1}, [])), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_import) ++ ++ def test_bp_ignore_count(self): ++ code = """ ++ def func(): ++ lno = 3 ++ ++ def main(): ++ for i in range(2): ++ func() ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ++ break_in_func('func', TEST_MODULE_FNAME), ++ ('None', 2, 'tfunc_import'), ('ignore', (1, )), ++ ('None', 2, 'tfunc_import'), ('continue', ), ++ ('line', 3, 'func', ({1:2}, [])), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_import) ++ ++ def test_ignore_count_on_disabled_bp(self): ++ code = """ ++ def func(): ++ lno = 3 ++ ++ def main(): ++ for i in range(3): ++ func() ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ++ break_in_func('func', TEST_MODULE_FNAME), ++ ('None', 2, 'tfunc_import'), ++ break_in_func('func', TEST_MODULE_FNAME), ++ ('None', 2, 'tfunc_import'), ('ignore', (1, )), ++ ('None', 2, 'tfunc_import'), ('disable', (1, )), ++ ('None', 2, 'tfunc_import'), ('continue', ), ++ ('line', 3, 'func', ({2:1}, [])), ('enable', (1, )), ++ ('None', 3, 'func'), ('continue', ), ++ ('line', 3, 'func', ({2:2}, [])), ('continue', ), ++ ('line', 3, 'func', ({1:2}, [])), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_import) ++ ++ def test_clear_two_bp_on_same_line(self): ++ code = """ ++ def func(): ++ lno = 3 ++ lno = 4 ++ ++ def main(): ++ for i in range(3): ++ func() ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ('break', (TEST_MODULE_FNAME, 3)), ++ ('None', 2, 'tfunc_import'), ('break', (TEST_MODULE_FNAME, 3)), ++ ('None', 2, 'tfunc_import'), ('break', (TEST_MODULE_FNAME, 4)), ++ ('None', 2, 'tfunc_import'), ('continue', ), ++ ('line', 3, 'func', ({1:1}, [])), ('continue', ), ++ ('line', 4, 'func', ({3:1}, [])), ('clear', (TEST_MODULE_FNAME, 3)), ++ ('None', 4, 'func'), ('continue', ), ++ ('line', 4, 'func', ({3:2}, [])), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_import) ++ ++ def test_clear_at_no_bp(self): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ('clear', (__file__, 1)) ++ ] ++ with TracerRun(self) as tracer: ++ self.assertRaises(BdbError, tracer.runcall, tfunc_import) ++ ++class RunTestCase(BaseTestCase): ++ """Test run, runeval and set_trace.""" ++ ++ def test_run_step(self): ++ # Check that the bdb 'run' method stops at the first line event. ++ code = """ ++ lno = 2 ++ """ ++ self.expect_set = [ ++ ('line', 2, ''), ('step', ), ++ ('return', 2, ''), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.run(compile(textwrap.dedent(code), '', 'exec')) ++ ++ def test_runeval_step(self): ++ # Test bdb 'runeval'. ++ code = """ ++ def main(): ++ lno = 3 ++ """ ++ modules = { TEST_MODULE: code } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 1, ''), ('step', ), ++ ('call', 2, 'main'), ('step', ), ++ ('line', 3, 'main'), ('step', ), ++ ('return', 3, 'main'), ('step', ), ++ ('return', 1, ''), ('quit', ), ++ ] ++ import test_module ++ with TracerRun(self) as tracer: ++ tracer.runeval('test_module.main()', globals(), locals()) ++ ++class IssuesTestCase(BaseTestCase): ++ """Test fixed bdb issues.""" ++ ++ def test_step_at_return_with_no_trace_in_caller(self): ++ # Issue #13183. ++ # Check that the tracer does step into the caller frame when the ++ # trace function is not set in that frame. ++ code_1 = """ ++ from test_module_2 import func ++ def main(): ++ func() ++ lno = 5 ++ """ ++ code_2 = """ ++ def func(): ++ lno = 3 ++ """ ++ modules = { ++ TEST_MODULE: code_1, ++ 'test_module_2': code_2, ++ } ++ with create_modules(modules): ++ self.expect_set = [ ++ ('line', 2, 'tfunc_import'), ++ break_in_func('func', 'test_module_2.py'), ++ ('None', 2, 'tfunc_import'), ('continue', ), ++ ('line', 3, 'func', ({1:1}, [])), ('step', ), ++ ('return', 3, 'func'), ('step', ), ++ ('line', 5, 'main'), ('quit', ), ++ ] ++ with TracerRun(self) as tracer: ++ tracer.runcall(tfunc_import) ++ ++def test_main(): ++ test.support.run_unittest( ++ StateTestCase, ++ RunTestCase, ++ BreakpointTestCase, ++ IssuesTestCase, ++ ) ++ ++if __name__ == "__main__": ++ test_main() +diff --git a/Lib/test/test_capi.py b/Lib/test/test_capi.py +index 944e9603cc..5eb3f7d4c7 100644 +--- a/Lib/test/test_capi.py ++++ b/Lib/test/test_capi.py +@@ -2,6 +2,7 @@ + # these are all functions _testcapi exports whose name begins with 'test_'. + + from __future__ import with_statement ++import string + import sys + import time + import random +@@ -101,6 +102,20 @@ class TestPendingCalls(unittest.TestCase): + self.pendingcalls_wait(l, n) + + ++class TestGetIndices(unittest.TestCase): ++ ++ def test_get_indices(self): ++ self.assertEqual(_testcapi.get_indices(slice(10L, 20, 1), 100), (0, 10, 20, 1)) ++ self.assertEqual(_testcapi.get_indices(slice(10.1, 20, 1), 100), None) ++ self.assertEqual(_testcapi.get_indices(slice(10, 20L, 1), 100), (0, 10, 20, 1)) ++ self.assertEqual(_testcapi.get_indices(slice(10, 20.1, 1), 100), None) ++ ++ self.assertEqual(_testcapi.get_indices(slice(10L, 20, 1L), 100), (0, 10, 20, 1)) ++ self.assertEqual(_testcapi.get_indices(slice(10.1, 20, 1L), 100), None) ++ self.assertEqual(_testcapi.get_indices(slice(10, 20L, 1L), 100), (0, 10, 20, 1)) ++ self.assertEqual(_testcapi.get_indices(slice(10, 20.1, 1L), 100), None) ++ ++ + @unittest.skipUnless(threading and thread, 'Threading required for this test.') + class TestThreadState(unittest.TestCase): + +@@ -126,18 +141,15 @@ class TestThreadState(unittest.TestCase): + t.join() + + ++class Test_testcapi(unittest.TestCase): ++ locals().update((name, getattr(_testcapi, name)) ++ for name in dir(_testcapi) ++ if name.startswith('test_') and not name.endswith('_code')) ++ ++ + def test_main(): +- for name in dir(_testcapi): +- if name.startswith('test_'): +- test = getattr(_testcapi, name) +- if support.verbose: +- print "internal", name +- try: +- test() +- except _testcapi.error: +- raise support.TestFailed, sys.exc_info()[1] +- +- support.run_unittest(CAPITest, TestPendingCalls, TestThreadState) ++ support.run_unittest(CAPITest, TestPendingCalls, ++ TestThreadState, TestGetIndices, Test_testcapi) + + if __name__ == "__main__": + test_main() +diff --git a/Lib/test/test_deque.py b/Lib/test/test_deque.py +index c81064d9f2..e6307ab5c3 100644 +--- a/Lib/test/test_deque.py ++++ b/Lib/test/test_deque.py +@@ -659,6 +659,21 @@ class TestSubclass(unittest.TestCase): + d1 == d2 # not clear if this is supposed to be True or False, + # but it used to give a SystemError + ++ @test_support.cpython_only ++ def test_bug_31608(self): ++ # The interpreter used to crash in specific cases where a deque ++ # subclass returned a non-deque. ++ class X(deque): ++ pass ++ d = X() ++ def bad___new__(cls, *args, **kwargs): ++ return [42] ++ X.__new__ = bad___new__ ++ with self.assertRaises(TypeError): ++ d * 42 # shouldn't crash ++ with self.assertRaises(TypeError): ++ d + deque([1, 2, 3]) # shouldn't crash ++ + + class SubclassWithKwargs(deque): + def __init__(self, newarg=1): +diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py +index 1fd7910d15..6bfc4e63e7 100644 +--- a/Lib/test/test_file.py ++++ b/Lib/test/test_file.py +@@ -12,7 +12,8 @@ from weakref import proxy + import io + import _pyio as pyio + +-from test.test_support import TESTFN, run_unittest ++from test.support import TESTFN, run_unittest ++from test import support + from UserList import UserList + + class AutoFileTests(unittest.TestCase): +@@ -24,7 +25,7 @@ class AutoFileTests(unittest.TestCase): + def tearDown(self): + if self.f: + self.f.close() +- os.remove(TESTFN) ++ support.unlink(TESTFN) + + def testWeakRefs(self): + # verify weak references +@@ -143,8 +144,12 @@ class PyAutoFileTests(AutoFileTests): + + class OtherFileTests(unittest.TestCase): + ++ def tearDown(self): ++ support.unlink(TESTFN) ++ + def testModeStrings(self): + # check invalid mode strings ++ self.open(TESTFN, 'wb').close() + for mode in ("", "aU", "wU+"): + try: + f = self.open(TESTFN, mode) +@@ -191,7 +196,6 @@ class OtherFileTests(unittest.TestCase): + # SF bug + # "file.truncate fault on windows" + +- os.unlink(TESTFN) + f = self.open(TESTFN, 'wb') + + try: +@@ -215,7 +219,6 @@ class OtherFileTests(unittest.TestCase): + self.fail("File size after ftruncate wrong %d" % size) + finally: + f.close() +- os.unlink(TESTFN) + + def testIteration(self): + # Test the complex interaction when mixing file-iteration and the +@@ -236,86 +239,82 @@ class OtherFileTests(unittest.TestCase): + methods = [("readline", ()), ("read", ()), ("readlines", ()), + ("readinto", (array("b", b" "*100),))] + +- try: +- # Prepare the testfile +- bag = self.open(TESTFN, "wb") +- bag.write(filler * nchunks) +- bag.writelines(testlines) +- bag.close() +- # Test for appropriate errors mixing read* and iteration +- for methodname, args in methods: +- f = self.open(TESTFN, 'rb') +- if next(f) != filler: +- self.fail, "Broken testfile" +- meth = getattr(f, methodname) +- meth(*args) # This simply shouldn't fail +- f.close() +- +- # Test to see if harmless (by accident) mixing of read* and +- # iteration still works. This depends on the size of the internal +- # iteration buffer (currently 8192,) but we can test it in a +- # flexible manner. Each line in the bag o' ham is 4 bytes +- # ("h", "a", "m", "\n"), so 4096 lines of that should get us +- # exactly on the buffer boundary for any power-of-2 buffersize +- # between 4 and 16384 (inclusive). ++ # Prepare the testfile ++ bag = self.open(TESTFN, "wb") ++ bag.write(filler * nchunks) ++ bag.writelines(testlines) ++ bag.close() ++ # Test for appropriate errors mixing read* and iteration ++ for methodname, args in methods: + f = self.open(TESTFN, 'rb') +- for i in range(nchunks): +- next(f) +- testline = testlines.pop(0) +- try: +- line = f.readline() +- except ValueError: +- self.fail("readline() after next() with supposedly empty " +- "iteration-buffer failed anyway") +- if line != testline: +- self.fail("readline() after next() with empty buffer " +- "failed. Got %r, expected %r" % (line, testline)) +- testline = testlines.pop(0) +- buf = array("b", b"\x00" * len(testline)) ++ self.assertEqual(next(f), filler) ++ meth = getattr(f, methodname) ++ meth(*args) # This simply shouldn't fail ++ f.close() ++ ++ # Test to see if harmless (by accident) mixing of read* and ++ # iteration still works. This depends on the size of the internal ++ # iteration buffer (currently 8192,) but we can test it in a ++ # flexible manner. Each line in the bag o' ham is 4 bytes ++ # ("h", "a", "m", "\n"), so 4096 lines of that should get us ++ # exactly on the buffer boundary for any power-of-2 buffersize ++ # between 4 and 16384 (inclusive). ++ f = self.open(TESTFN, 'rb') ++ for i in range(nchunks): ++ next(f) ++ testline = testlines.pop(0) ++ try: ++ line = f.readline() ++ except ValueError: ++ self.fail("readline() after next() with supposedly empty " ++ "iteration-buffer failed anyway") ++ if line != testline: ++ self.fail("readline() after next() with empty buffer " ++ "failed. Got %r, expected %r" % (line, testline)) ++ testline = testlines.pop(0) ++ buf = array("b", b"\x00" * len(testline)) ++ try: ++ f.readinto(buf) ++ except ValueError: ++ self.fail("readinto() after next() with supposedly empty " ++ "iteration-buffer failed anyway") ++ line = buf.tostring() ++ if line != testline: ++ self.fail("readinto() after next() with empty buffer " ++ "failed. Got %r, expected %r" % (line, testline)) ++ ++ testline = testlines.pop(0) ++ try: ++ line = f.read(len(testline)) ++ except ValueError: ++ self.fail("read() after next() with supposedly empty " ++ "iteration-buffer failed anyway") ++ if line != testline: ++ self.fail("read() after next() with empty buffer " ++ "failed. Got %r, expected %r" % (line, testline)) ++ try: ++ lines = f.readlines() ++ except ValueError: ++ self.fail("readlines() after next() with supposedly empty " ++ "iteration-buffer failed anyway") ++ if lines != testlines: ++ self.fail("readlines() after next() with empty buffer " ++ "failed. Got %r, expected %r" % (line, testline)) ++ # Reading after iteration hit EOF shouldn't hurt either ++ f.close() ++ f = self.open(TESTFN, 'rb') ++ try: ++ for line in f: ++ pass + try: ++ f.readline() + f.readinto(buf) ++ f.read() ++ f.readlines() + except ValueError: +- self.fail("readinto() after next() with supposedly empty " +- "iteration-buffer failed anyway") +- line = buf.tostring() +- if line != testline: +- self.fail("readinto() after next() with empty buffer " +- "failed. Got %r, expected %r" % (line, testline)) +- +- testline = testlines.pop(0) +- try: +- line = f.read(len(testline)) +- except ValueError: +- self.fail("read() after next() with supposedly empty " +- "iteration-buffer failed anyway") +- if line != testline: +- self.fail("read() after next() with empty buffer " +- "failed. Got %r, expected %r" % (line, testline)) +- try: +- lines = f.readlines() +- except ValueError: +- self.fail("readlines() after next() with supposedly empty " +- "iteration-buffer failed anyway") +- if lines != testlines: +- self.fail("readlines() after next() with empty buffer " +- "failed. Got %r, expected %r" % (line, testline)) +- # Reading after iteration hit EOF shouldn't hurt either +- f.close() +- f = self.open(TESTFN, 'rb') +- try: +- for line in f: +- pass +- try: +- f.readline() +- f.readinto(buf) +- f.read() +- f.readlines() +- except ValueError: +- self.fail("read* failed after next() consumed file") +- finally: +- f.close() ++ self.fail("read* failed after next() consumed file") + finally: +- os.unlink(TESTFN) ++ f.close() + + class COtherFileTests(OtherFileTests): + open = io.open +@@ -325,14 +324,8 @@ class PyOtherFileTests(OtherFileTests): + + + def test_main(): +- # Historically, these tests have been sloppy about removing TESTFN. +- # So get rid of it no matter what. +- try: +- run_unittest(CAutoFileTests, PyAutoFileTests, +- COtherFileTests, PyOtherFileTests) +- finally: +- if os.path.exists(TESTFN): +- os.unlink(TESTFN) ++ run_unittest(CAutoFileTests, PyAutoFileTests, ++ COtherFileTests, PyOtherFileTests) + + if __name__ == '__main__': + test_main() +diff --git a/Lib/test/test_ftplib.py b/Lib/test/test_ftplib.py +index e728aa70f9..8a3eb067a4 100644 +--- a/Lib/test/test_ftplib.py ++++ b/Lib/test/test_ftplib.py +@@ -675,6 +675,7 @@ class TestTLS_FTPClass(TestCase): + # clear text + sock = self.client.transfercmd('list') + self.assertNotIsInstance(sock, ssl.SSLSocket) ++ self.assertEqual(sock.recv(1024), LIST_DATA.encode('ascii')) + sock.close() + self.assertEqual(self.client.voidresp(), "226 transfer complete") + +@@ -682,6 +683,9 @@ class TestTLS_FTPClass(TestCase): + self.client.prot_p() + sock = self.client.transfercmd('list') + self.assertIsInstance(sock, ssl.SSLSocket) ++ # consume from SSL socket to finalize handshake and avoid ++ # "SSLError [SSL] shutdown while in init" ++ self.assertEqual(sock.recv(1024), LIST_DATA.encode('ascii')) + sock.close() + self.assertEqual(self.client.voidresp(), "226 transfer complete") + +@@ -689,6 +693,7 @@ class TestTLS_FTPClass(TestCase): + self.client.prot_c() + sock = self.client.transfercmd('list') + self.assertNotIsInstance(sock, ssl.SSLSocket) ++ self.assertEqual(sock.recv(1024), LIST_DATA.encode('ascii')) + sock.close() + self.assertEqual(self.client.voidresp(), "226 transfer complete") + +diff --git a/Lib/test/test_gdb.py b/Lib/test/test_gdb.py +index dce3c5cdc7..c45fd45735 100644 +--- a/Lib/test/test_gdb.py ++++ b/Lib/test/test_gdb.py +@@ -3,13 +3,14 @@ + # The code for testing gdb was adapted from similar work in Unladen Swallow's + # Lib/test/test_jit_gdb.py + ++import locale + import os + import re + import subprocess + import sys + import sysconfig ++import textwrap + import unittest +-import sysconfig + + from test import test_support + from test.test_support import run_unittest, findfile +@@ -214,6 +215,15 @@ class DebuggerTests(unittest.TestCase): + for line in errlines: + if not line: + continue ++ # bpo34007: Sometimes some versions of the shared libraries that ++ # are part of the traceback are compiled in optimised mode and the ++ # Program Counter (PC) is not present, not allowing gdb to walk the ++ # frames back. When this happens, the Python bindings of gdb raise ++ # an exception, making the test impossible to succeed. ++ if "PC not saved" in line: ++ raise unittest.SkipTest("gdb cannot walk the frame object" ++ " because the Program Counter is" ++ " not present") + if not line.startswith(ignore_patterns): + unexpected_errlines.append(line) + +@@ -863,7 +873,24 @@ print 42 + breakpoint='time_gmtime', + cmds_after_breakpoint=['py-bt-full'], + ) +- self.assertIn('#0 size2 >= size0) ++ self.assertLess(size2, size1) ++ self.assertGreaterEqual(size2, size0) + + + def test_main(): +diff --git a/Lib/test/test_getargs2.py b/Lib/test/test_getargs2.py +index e0efcaae9c..7f819fb10c 100644 +--- a/Lib/test/test_getargs2.py ++++ b/Lib/test/test_getargs2.py +@@ -1,9 +1,10 @@ + import unittest + import math ++import string + import sys + from test import test_support + # Skip this test if the _testcapi module isn't available. +-test_support.import_module('_testcapi') ++_testcapi = test_support.import_module('_testcapi') + from _testcapi import getargs_keywords + import warnings + +@@ -799,12 +800,6 @@ class Unicode_TestCase(unittest.TestCase): + self.assertRaises(TypeError, getargs_u_hash, None) + + +-def test_main(): +- tests = [Signed_TestCase, Unsigned_TestCase, LongLong_TestCase, +- Tuple_TestCase, Keywords_TestCase, +- Bytes_TestCase, String_TestCase, Unicode_TestCase] +- test_support.run_unittest(*tests) +- + class Object_TestCase(unittest.TestCase): + def test_S(self): + from _testcapi import getargs_S +@@ -840,5 +835,142 @@ class Object_TestCase(unittest.TestCase): + self.assertRaises(TypeError, getargs_U, buffer(obj)) + + ++class SkipitemTest(unittest.TestCase): ++ ++ def test_skipitem(self): ++ """ ++ If this test failed, you probably added a new "format unit" ++ in Python/getargs.c, but neglected to update our poor friend ++ skipitem() in the same file. (If so, shame on you!) ++ ++ With a few exceptions**, this function brute-force tests all ++ printable ASCII*** characters (32 to 126 inclusive) as format units, ++ checking to see that PyArg_ParseTupleAndKeywords() return consistent ++ errors both when the unit is attempted to be used and when it is ++ skipped. If the format unit doesn't exist, we'll get one of two ++ specific error messages (one for used, one for skipped); if it does ++ exist we *won't* get that error--we'll get either no error or some ++ other error. If we get the specific "does not exist" error for one ++ test and not for the other, there's a mismatch, and the test fails. ++ ++ ** Some format units have special funny semantics and it would ++ be difficult to accommodate them here. Since these are all ++ well-established and properly skipped in skipitem() we can ++ get away with not testing them--this test is really intended ++ to catch *new* format units. ++ ++ *** Python C source files must be ASCII. Therefore it's impossible ++ to have non-ASCII format units. ++ ++ """ ++ empty_tuple = () ++ tuple_1 = (0,) ++ dict_b = {'b':1} ++ keywords = ["a", "b"] ++ ++ for i in range(32, 127): ++ c = chr(i) ++ ++ # skip parentheses, the error reporting is inconsistent about them ++ # skip 'e', it's always a two-character code ++ # skip '|', it doesn't represent arguments anyway ++ if c in '()e|': ++ continue ++ ++ # test the format unit when not skipped ++ format = c + "i" ++ try: ++ _testcapi.parse_tuple_and_keywords(tuple_1, dict_b, ++ format, keywords) ++ when_not_skipped = False ++ except TypeError as e: ++ s = "argument 1 (impossible)" ++ when_not_skipped = (str(e) == s) ++ except RuntimeError: ++ when_not_skipped = False ++ ++ # test the format unit when skipped ++ optional_format = "|" + format ++ try: ++ _testcapi.parse_tuple_and_keywords(empty_tuple, dict_b, ++ optional_format, keywords) ++ when_skipped = False ++ except RuntimeError as e: ++ s = "impossible: '{}'".format(format) ++ when_skipped = (str(e) == s) ++ ++ message = ("test_skipitem_parity: " ++ "detected mismatch between convertsimple and skipitem " ++ "for format unit '{}' ({}), not skipped {}, skipped {}".format( ++ c, i, when_skipped, when_not_skipped)) ++ self.assertIs(when_skipped, when_not_skipped, message) ++ ++ def test_skipitem_with_suffix(self): ++ parse = _testcapi.parse_tuple_and_keywords ++ empty_tuple = () ++ tuple_1 = (0,) ++ dict_b = {'b':1} ++ keywords = ["a", "b"] ++ ++ supported = ('s#', 's*', 'z#', 'z*', 'u#', 't#', 'w#', 'w*') ++ for c in string.ascii_letters: ++ for c2 in '#*': ++ f = c + c2 ++ optional_format = "|" + f + "i" ++ if f in supported: ++ parse(empty_tuple, dict_b, optional_format, keywords) ++ else: ++ with self.assertRaisesRegexp((RuntimeError, TypeError), ++ 'impossible'): ++ parse(empty_tuple, dict_b, optional_format, keywords) ++ ++ for c in map(chr, range(32, 128)): ++ f = 'e' + c ++ optional_format = "|" + f + "i" ++ if c in 'st': ++ parse(empty_tuple, dict_b, optional_format, keywords) ++ else: ++ with self.assertRaisesRegexp(RuntimeError, ++ 'impossible'): ++ parse(empty_tuple, dict_b, optional_format, keywords) ++ ++ ++class ParseTupleAndKeywords_Test(unittest.TestCase): ++ ++ def test_parse_tuple_and_keywords(self): ++ # Test handling errors in the parse_tuple_and_keywords helper itself ++ self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords, ++ (), {}, 42, []) ++ self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords, ++ (), {}, '', 42) ++ self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords, ++ (), {}, '', [''] * 42) ++ self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords, ++ (), {}, '', [42]) ++ ++ def test_bad_use(self): ++ # Test handling invalid format and keywords in ++ # PyArg_ParseTupleAndKeywords() ++ self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords, ++ (1,), {}, '||O', ['a']) ++ self.assertRaises(RuntimeError, _testcapi.parse_tuple_and_keywords, ++ (1,), {}, '|O', ['a', 'b']) ++ self.assertRaises(RuntimeError, _testcapi.parse_tuple_and_keywords, ++ (1,), {}, '|OO', ['a']) ++ ++ ++class Test_testcapi(unittest.TestCase): ++ locals().update((name, getattr(_testcapi, name)) ++ for name in dir(_testcapi) ++ if name.startswith('test_') and name.endswith('_code')) ++ ++ ++def test_main(): ++ tests = [Signed_TestCase, Unsigned_TestCase, LongLong_TestCase, ++ Tuple_TestCase, Keywords_TestCase, ++ Bytes_TestCase, String_TestCase, Unicode_TestCase, ++ SkipitemTest, ParseTupleAndKeywords_Test, Test_testcapi] ++ test_support.run_unittest(*tests) ++ + if __name__ == "__main__": + test_main() +diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py +index 23b6ce8d3c..228586ece0 100644 +--- a/Lib/test/test_grammar.py ++++ b/Lib/test/test_grammar.py +@@ -5,6 +5,7 @@ from test.test_support import run_unittest, check_syntax_error, \ + check_py3k_warnings + import unittest + import sys ++import warnings + # testing import * + from sys import * + +@@ -628,7 +629,6 @@ hello world + with check_py3k_warnings((warntext, DeprecationWarning)): + compile(code, '', 'exec') + if sys.py3kwarning: +- import warnings + with warnings.catch_warnings(): + warnings.filterwarnings('error', category=DeprecationWarning) + with self.assertRaises(SyntaxError) as cm: +@@ -883,6 +883,13 @@ hello world + with check_py3k_warnings(('<> not supported in 3.x; use !=', + DeprecationWarning)): + if eval('1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1'): pass ++ if sys.py3kwarning: ++ with warnings.catch_warnings(): ++ warnings.filterwarnings('error', category=DeprecationWarning) ++ with self.assertRaises(DeprecationWarning) as cm: ++ compile('1 <> 1', '', 'eval') ++ self.assertIn('<> not supported in 3.x; use !=', ++ str(cm.exception)) + + def test_binary_mask_ops(self): + x = 1 & 1 +diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py +index 902d93fe04..cdb1af5c3d 100644 +--- a/Lib/test/test_gzip.py ++++ b/Lib/test/test_gzip.py +@@ -6,6 +6,7 @@ from test import test_support + import os + import io + import struct ++import tempfile + gzip = test_support.import_module('gzip') + + data1 = """ int length=DEFAULTALLOC, err = Z_OK; +@@ -331,6 +332,12 @@ class TestGzip(unittest.TestCase): + with gzip.GzipFile(fileobj=f, mode="w") as g: + self.assertEqual(g.name, "") + ++ def test_fileobj_from_io_open(self): ++ fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT) ++ with io.open(fd, "wb") as f: ++ with gzip.GzipFile(fileobj=f, mode="w") as g: ++ self.assertEqual(g.name, "") ++ + def test_fileobj_mode(self): + gzip.GzipFile(self.filename, "wb").close() + with open(self.filename, "r+b") as f: +@@ -359,6 +366,14 @@ class TestGzip(unittest.TestCase): + with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f: + self.assertEqual(f.read(), b'Test') + ++ def test_fileobj_without_name(self): ++ # Issue #33038: GzipFile should not assume that file objects that have ++ # a .name attribute use a non-None value. ++ with tempfile.SpooledTemporaryFile() as f: ++ with gzip.GzipFile(fileobj=f, mode='wb') as archive: ++ archive.write(b'data') ++ self.assertEqual(archive.name, '') ++ + def test_main(verbose=None): + test_support.run_unittest(TestGzip) + +diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py +index 471ebb4dd1..b8d6388fea 100644 +--- a/Lib/test/test_hashlib.py ++++ b/Lib/test/test_hashlib.py +@@ -371,25 +371,25 @@ class HashLibTestCase(unittest.TestCase): + data = smallest_data*200000 + expected_hash = hashlib.sha1(data*num_threads).hexdigest() + +- def hash_in_chunks(chunk_size, event): ++ def hash_in_chunks(chunk_size): + index = 0 + while index < len(data): + hasher.update(data[index:index+chunk_size]) + index += chunk_size +- event.set() + +- events = [] ++ threads = [] + for threadnum in xrange(num_threads): + chunk_size = len(data) // (10**threadnum) + assert chunk_size > 0 + assert chunk_size % len(smallest_data) == 0 +- event = threading.Event() +- events.append(event) +- threading.Thread(target=hash_in_chunks, +- args=(chunk_size, event)).start() +- +- for event in events: +- event.wait() ++ thread = threading.Thread(target=hash_in_chunks, ++ args=(chunk_size,)) ++ threads.append(thread) ++ ++ for thread in threads: ++ thread.start() ++ for thread in threads: ++ thread.join() + + self.assertEqual(expected_hash, hasher.hexdigest()) + +diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py +index 11f0d5d614..93807c1959 100644 +--- a/Lib/test/test_httpservers.py ++++ b/Lib/test/test_httpservers.py +@@ -66,6 +66,7 @@ class TestServerThread(threading.Thread): + + def stop(self): + self.server.shutdown() ++ self.join() + + + class BaseTestCase(unittest.TestCase): +diff --git a/Lib/test/test_import_magic.py b/Lib/test/test_import_magic.py +index 92f68b44f2..57e350e3d8 100644 +--- a/Lib/test/test_import_magic.py ++++ b/Lib/test/test_import_magic.py +@@ -11,7 +11,7 @@ class MagicNumberTests(unittest.TestCase): + Test release compatibility issues relating to precompiled bytecode + """ + @unittest.skipUnless( +- sys.version_info.releaselevel in ('final', 'release'), ++ sys.version_info.releaselevel in ('candidate', 'final'), + 'only applies to candidate or final python release levels' + ) + def test_magic_number(self): +diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py +index 7d09c6fa02..5063a30d22 100644 +--- a/Lib/test/test_inspect.py ++++ b/Lib/test/test_inspect.py +@@ -209,7 +209,7 @@ class GetSourceBase(unittest.TestCase): + + def sourcerange(self, top, bottom): + lines = self.source.split("\n") +- return "\n".join(lines[top-1:bottom]) + "\n" ++ return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "") + + def assertSourceEqual(self, obj, top, bottom): + self.assertEqual(inspect.getsource(obj), +@@ -331,6 +331,16 @@ class TestRetrievingSourceCode(GetSourceBase): + finally: + linecache.getlines = getlines + ++class TestGettingSourceOfToplevelFrames(GetSourceBase): ++ fodderFile = mod ++ ++ def test_range_toplevel_frame(self): ++ self.maxDiff = None ++ self.assertSourceEqual(mod.currentframe, 1, None) ++ ++ def test_range_traceback_toplevel_frame(self): ++ self.assertSourceEqual(mod.tb, 1, None) ++ + class TestDecorators(GetSourceBase): + fodderFile = mod2 + +@@ -896,7 +906,8 @@ def test_main(): + TestDecorators, TestRetrievingSourceCode, TestOneliners, TestBuggyCases, + TestInterpreterStack, TestClassesAndFunctions, TestPredicates, + TestGetcallargsFunctions, TestGetcallargsFunctionsCellVars, +- TestGetcallargsMethods, TestGetcallargsUnboundMethods) ++ TestGetcallargsMethods, TestGetcallargsUnboundMethods, ++ TestGettingSourceOfToplevelFrames) + + if __name__ == "__main__": + test_main() +diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py +index ea5ec656f7..26c5dfe926 100644 +--- a/Lib/test/test_io.py ++++ b/Lib/test/test_io.py +@@ -690,6 +690,16 @@ class IOTest(unittest.TestCase): + self.assertEqual(stream.readinto(buffer), 5) + self.assertEqual(buffer.tobytes(), b"12345") + ++ def test_close_assert(self): ++ class R(self.IOBase): ++ def __setattr__(self, name, value): ++ pass ++ def flush(self): ++ raise OSError() ++ f = R() ++ # This would cause an assertion failure. ++ self.assertRaises(OSError, f.close) ++ + + class CIOTest(IOTest): + +@@ -1091,6 +1101,7 @@ class CBufferedReaderTest(BufferedReaderTest, SizeofTest): + def test_garbage_collection(self): + # C BufferedReader objects are collected. + # The Python version has __del__, so it ends into gc.garbage instead ++ self.addCleanup(support.unlink, support.TESTFN) + rawio = self.FileIO(support.TESTFN, "w+b") + f = self.tp(rawio) + f.f = f +@@ -1292,6 +1303,7 @@ class BufferedWriterTest(unittest.TestCase, CommonBufferedTests): + + def test_truncate(self): + # Truncate implicitly flushes the buffer. ++ self.addCleanup(support.unlink, support.TESTFN) + with self.open(support.TESTFN, self.write_mode, buffering=0) as raw: + bufio = self.tp(raw, 8) + bufio.write(b"abcdef") +@@ -1398,6 +1410,7 @@ class CBufferedWriterTest(BufferedWriterTest, SizeofTest): + # C BufferedWriter objects are collected, and collecting them flushes + # all data to disk. + # The Python version has __del__, so it ends into gc.garbage instead ++ self.addCleanup(support.unlink, support.TESTFN) + rawio = self.FileIO(support.TESTFN, "w+b") + f = self.tp(rawio) + f.write(b"123xxx") +@@ -2738,6 +2751,17 @@ class TextIOWrapperTest(unittest.TestCase): + with self.maybeRaises(TypeError): + t.read(42) + ++ def test_issue25862(self): ++ # Assertion failures occurred in tell() after read() and write(). ++ t = self.TextIOWrapper(self.BytesIO(b'test'), encoding='ascii') ++ t.read(1) ++ t.read() ++ t.tell() ++ t = self.TextIOWrapper(self.BytesIO(b'test'), encoding='ascii') ++ t.read(1) ++ t.write('x') ++ t.tell() ++ + + class CTextIOWrapperTest(TextIOWrapperTest): + +@@ -3146,7 +3170,6 @@ class SignalsTest(unittest.TestCase): + try: + wio = self.io.open(w, **fdopen_kwargs) + t.start() +- signal.alarm(1) + # Fill the pipe enough that the write will be blocking. + # It will be interrupted by the timer armed above. Since the + # other thread has read one byte, the low-level write will +@@ -3154,10 +3177,13 @@ class SignalsTest(unittest.TestCase): + # The buffered IO layer must check for pending signal + # handlers, which in this case will invoke alarm_interrupt(). + try: ++ signal.alarm(1) + with self.assertRaises(ZeroDivisionError): + wio.write(item * (support.PIPE_MAX_SIZE // len(item) + 1)) + finally: ++ signal.alarm(0) + t.join() ++ + # We got one byte, get another one and check that it isn't a + # repeat of the first one. + read_results.append(os.read(r, 1)) +@@ -3206,6 +3232,7 @@ class SignalsTest(unittest.TestCase): + if isinstance(exc, RuntimeError): + self.assertTrue(str(exc).startswith("reentrant call"), str(exc)) + finally: ++ signal.alarm(0) + wio.close() + os.close(r) + +@@ -3234,6 +3261,7 @@ class SignalsTest(unittest.TestCase): + # - third raw read() returns b"bar" + self.assertEqual(decode(rio.read(6)), "foobar") + finally: ++ signal.alarm(0) + rio.close() + os.close(w) + os.close(r) +@@ -3295,6 +3323,7 @@ class SignalsTest(unittest.TestCase): + self.assertIsNone(error[0]) + self.assertEqual(N, sum(len(x) for x in read_results)) + finally: ++ signal.alarm(0) + write_finished = True + os.close(w) + os.close(r) +diff --git a/Lib/test/test_locale.py b/Lib/test/test_locale.py +index 563ddb144f..6070882a37 100644 +--- a/Lib/test/test_locale.py ++++ b/Lib/test/test_locale.py +@@ -425,7 +425,7 @@ class NormalizeTest(unittest.TestCase): + + def test_valencia_modifier(self): + self.check('ca_ES.UTF-8@valencia', 'ca_ES.UTF-8@valencia') +- self.check('ca_ES@valencia', 'ca_ES.ISO8859-15@valencia') ++ self.check('ca_ES@valencia', 'ca_ES.UTF-8@valencia') + self.check('ca@valencia', 'ca_ES.ISO8859-1@valencia') + + def test_devanagari_modifier(self): +diff --git a/Lib/test/test_marshal.py b/Lib/test/test_marshal.py +index 76d59bac39..bbaa9442ab 100644 +--- a/Lib/test/test_marshal.py ++++ b/Lib/test/test_marshal.py +@@ -227,8 +227,22 @@ class BugsTestCase(unittest.TestCase): + pass + + def test_loads_recursion(self): +- s = 'c' + ('X' * 4*4) + '{' * 2**20 +- self.assertRaises(ValueError, marshal.loads, s) ++ def run_tests(N, check): ++ # (((...None...),),) ++ check(b'(\x01\x00\x00\x00' * N + b'N') ++ # [[[...None...]]] ++ check(b'[\x01\x00\x00\x00' * N + b'N') ++ # {None: {None: {None: ...None...}}} ++ check(b'{N' * N + b'N' + b'0' * N) ++ # frozenset([frozenset([frozenset([...None...])])]) ++ check(b'>\x01\x00\x00\x00' * N + b'N') ++ # Check that the generated marshal data is valid and marshal.loads() ++ # works for moderately deep nesting ++ run_tests(100, marshal.loads) ++ # Very deeply nested structure shouldn't blow the stack ++ def check(s): ++ self.assertRaises(ValueError, marshal.loads, s) ++ run_tests(2**20, check) + + def test_recursion_limit(self): + # Create a deeply nested structure. +diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py +index 0350b3de38..fc6d6e1cac 100644 +--- a/Lib/test/test_mmap.py ++++ b/Lib/test/test_mmap.py +@@ -666,6 +666,13 @@ class MmapTests(unittest.TestCase): + self.assertRaises(ValueError, m.write_byte, 'b') + self.assertRaises(ValueError, m.write, 'abc') + ++ def test_concat_repeat_exception(self): ++ m = mmap.mmap(-1, 16) ++ with self.assertRaises(TypeError): ++ m + m ++ with self.assertRaises(TypeError): ++ m * 2 ++ + + class LargeMmapTests(unittest.TestCase): + +diff --git a/Lib/test/test_multiprocessing.py b/Lib/test/test_multiprocessing.py +index 1071d7fac6..ff299feed8 100644 +--- a/Lib/test/test_multiprocessing.py ++++ b/Lib/test/test_multiprocessing.py +@@ -16,16 +16,16 @@ import logging + import errno + import weakref + import test.script_helper +-from test import test_support ++from test import support + from StringIO import StringIO +-_multiprocessing = test_support.import_module('_multiprocessing') ++_multiprocessing = support.import_module('_multiprocessing') + # import threading after _multiprocessing to raise a more relevant error + # message: "No module named _multiprocessing". _multiprocessing is not compiled + # without thread support. + import threading + + # Work around broken sem_open implementations +-test_support.import_module('multiprocessing.synchronize') ++support.import_module('multiprocessing.synchronize') + + import multiprocessing.dummy + import multiprocessing.connection +@@ -341,8 +341,8 @@ class _TestProcess(BaseTestCase): + if self.TYPE == 'threads': + self.skipTest('test not appropriate for {}'.format(self.TYPE)) + +- testfn = test_support.TESTFN +- self.addCleanup(test_support.unlink, testfn) ++ testfn = support.TESTFN ++ self.addCleanup(support.unlink, testfn) + + for reason, code in (([1, 2, 3], 1), ('ignore this', 1)): + p = self.Process(target=self._test_sys_exit, args=(reason, testfn)) +@@ -640,7 +640,7 @@ class _TestQueue(BaseTestCase): + p.join() + + def test_no_import_lock_contention(self): +- with test_support.temp_cwd(): ++ with support.temp_cwd(): + module_name = 'imported_by_an_imported_module' + with open(module_name + '.py', 'w') as f: + f.write("""if 1: +@@ -652,7 +652,7 @@ class _TestQueue(BaseTestCase): + q.close() + """) + +- with test_support.DirsOnSysPath(os.getcwd()): ++ with support.DirsOnSysPath(os.getcwd()): + try: + __import__(module_name) + except Queue.Empty: +@@ -1135,6 +1135,16 @@ class _TestContainers(BaseTestCase): + a.append('hello') + self.assertEqual(f[:], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'hello']]) + ++ def test_list_iter(self): ++ a = self.list(range(10)) ++ it = iter(a) ++ self.assertEqual(list(it), range(10)) ++ self.assertEqual(list(it), []) # exhausted ++ # list modified during iteration ++ it = iter(a) ++ a[0] = 100 ++ self.assertEqual(next(it), 100) ++ + def test_dict(self): + d = self.dict() + indices = range(65, 70) +@@ -1145,6 +1155,19 @@ class _TestContainers(BaseTestCase): + self.assertEqual(sorted(d.values()), [chr(i) for i in indices]) + self.assertEqual(sorted(d.items()), [(i, chr(i)) for i in indices]) + ++ def test_dict_iter(self): ++ d = self.dict() ++ indices = range(65, 70) ++ for i in indices: ++ d[i] = chr(i) ++ it = iter(d) ++ self.assertEqual(list(it), indices) ++ self.assertEqual(list(it), []) # exhausted ++ # dictionary changed size during iteration ++ it = iter(d) ++ d.clear() ++ self.assertRaises(RuntimeError, next, it) ++ + def test_namespace(self): + n = self.Namespace() + n.name = 'Bob' +@@ -1260,10 +1283,10 @@ class _TestPool(BaseTestCase): + self.assertRaises(SayWhenError, it.next) + + def test_imap_unordered(self): +- it = self.pool.imap_unordered(sqr, range(1000)) +- self.assertEqual(sorted(it), map(sqr, range(1000))) ++ it = self.pool.imap_unordered(sqr, range(100)) ++ self.assertEqual(sorted(it), map(sqr, range(100))) + +- it = self.pool.imap_unordered(sqr, range(1000), chunksize=53) ++ it = self.pool.imap_unordered(sqr, range(1000), chunksize=100) + self.assertEqual(sorted(it), map(sqr, range(1000))) + + def test_imap_unordered_handle_iterable_exception(self): +@@ -1517,10 +1540,10 @@ class _TestRemoteManager(BaseTestCase): + #'hall\xc3\xa5 v\xc3\xa4rlden'] # UTF-8 + ] + result = values[:] +- if test_support.have_unicode: ++ if support.have_unicode: + #result[-1] = u'hall\xe5 v\xe4rlden' +- uvalue = test_support.u(r'\u043f\u0440\u0438\u0432\u0456\u0442 ' +- r'\u0441\u0432\u0456\u0442') ++ uvalue = support.u(r'\u043f\u0440\u0438\u0432\u0456\u0442 ' ++ r'\u0441\u0432\u0456\u0442') + values.append(uvalue) + result.append(uvalue) + +@@ -1538,7 +1561,7 @@ class _TestRemoteManager(BaseTestCase): + authkey = os.urandom(32) + + manager = QueueManager( +- address=(test.test_support.HOST, 0), authkey=authkey, serializer=SERIALIZER ++ address=(test.support.HOST, 0), authkey=authkey, serializer=SERIALIZER + ) + manager.start() + +@@ -1575,7 +1598,7 @@ class _TestManagerRestart(BaseTestCase): + def test_rapid_restart(self): + authkey = os.urandom(32) + manager = QueueManager( +- address=(test.test_support.HOST, 0), authkey=authkey, serializer=SERIALIZER) ++ address=(test.support.HOST, 0), authkey=authkey, serializer=SERIALIZER) + srvr = manager.get_server() + addr = srvr.address + # Close the connection.Listener socket which gets opened as a part +@@ -1786,13 +1809,13 @@ class _TestConnection(BaseTestCase): + p = self.Process(target=self._writefd, args=(child_conn, b"foo")) + p.daemon = True + p.start() +- with open(test_support.TESTFN, "wb") as f: ++ with open(support.TESTFN, "wb") as f: + fd = f.fileno() + if msvcrt: + fd = msvcrt.get_osfhandle(fd) + reduction.send_handle(conn, fd, p.pid) + p.join() +- with open(test_support.TESTFN, "rb") as f: ++ with open(support.TESTFN, "rb") as f: + self.assertEqual(f.read(), b"foo") + + @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction") +@@ -1811,7 +1834,7 @@ class _TestConnection(BaseTestCase): + p = self.Process(target=self._writefd, args=(child_conn, b"bar", True)) + p.daemon = True + p.start() +- with open(test_support.TESTFN, "wb") as f: ++ with open(support.TESTFN, "wb") as f: + fd = f.fileno() + for newfd in range(256, MAXFD): + if not self._is_fd_assigned(newfd): +@@ -1824,7 +1847,7 @@ class _TestConnection(BaseTestCase): + finally: + os.close(newfd) + p.join() +- with open(test_support.TESTFN, "rb") as f: ++ with open(support.TESTFN, "rb") as f: + self.assertEqual(f.read(), b"bar") + + @classmethod +@@ -2207,7 +2230,7 @@ class _TestFinalize(BaseTestCase): + gc.set_threshold(5, 5, 5) + threads = [threading.Thread(target=run_finalizers), + threading.Thread(target=make_finalizers)] +- with test_support.start_threads(threads): ++ with support.start_threads(threads): + time.sleep(4.0) # Wait a bit to trigger race condition + finish = True + if exc: +@@ -2635,7 +2658,7 @@ class TestFlags(unittest.TestCase): + flags = (tuple(sys.flags), grandchild_flags) + print(json.dumps(flags)) + +- @test_support.requires_unicode # XXX json needs unicode support ++ @support.requires_unicode # XXX json needs unicode support + def test_flags(self): + import json, subprocess + # start child process using unusual flags +@@ -2681,6 +2704,9 @@ class TestForkAwareThreadLock(unittest.TestCase): + + class TestIgnoreEINTR(unittest.TestCase): + ++ # Sending CONN_MAX_SIZE bytes into a multiprocessing pipe must block ++ CONN_MAX_SIZE = max(support.PIPE_MAX_SIZE, support.SOCK_MAX_SIZE) ++ + @classmethod + def _test_ignore(cls, conn): + def handler(signum, frame): +@@ -2689,7 +2715,7 @@ class TestIgnoreEINTR(unittest.TestCase): + conn.send('ready') + x = conn.recv() + conn.send(x) +- conn.send_bytes(b'x'*(1024*1024)) # sending 1 MB should block ++ conn.send_bytes(b'x' * cls.CONN_MAX_SIZE) + + @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1') + def test_ignore(self): +@@ -2708,7 +2734,7 @@ class TestIgnoreEINTR(unittest.TestCase): + self.assertEqual(conn.recv(), 1234) + time.sleep(0.1) + os.kill(p.pid, signal.SIGUSR1) +- self.assertEqual(conn.recv_bytes(), b'x'*(1024*1024)) ++ self.assertEqual(conn.recv_bytes(), b'x' * self.CONN_MAX_SIZE) + time.sleep(0.1) + p.join() + finally: +@@ -2765,7 +2791,7 @@ def test_main(run=None): + check_enough_semaphores() + + if run is None: +- from test.test_support import run_unittest as run ++ from test.support import run_unittest as run + + util.get_temp_dir() # creates temp directory for use by all processes + +@@ -2790,7 +2816,7 @@ def test_main(run=None): + # module during these tests is at least platform dependent and possibly + # non-deterministic on any given platform. So we don't mind if the listed + # warnings aren't actually raised. +- with test_support.check_py3k_warnings( ++ with support.check_py3k_warnings( + (".+__(get|set)slice__ has been removed", DeprecationWarning), + (r"sys.exc_clear\(\) not supported", DeprecationWarning), + quiet=True): +diff --git a/Lib/test/test_parser.py b/Lib/test/test_parser.py +index 34b9cbb8c1..73974a96f0 100644 +--- a/Lib/test/test_parser.py ++++ b/Lib/test/test_parser.py +@@ -263,21 +263,19 @@ class RoundtripLegalSyntaxTestCase(unittest.TestCase): + # An absolutely minimal test of position information. Better + # tests would be a big project. + code = "def f(x):\n return x + 1" +- st1 = parser.suite(code) +- st2 = st1.totuple(line_info=1, col_info=1) ++ st = parser.suite(code) + + def walk(tree): + node_type = tree[0] + next = tree[1] +- if isinstance(next, tuple): ++ if isinstance(next, (tuple, list)): + for elt in tree[1:]: + for x in walk(elt): + yield x + else: + yield tree + +- terminals = list(walk(st2)) +- self.assertEqual([ ++ expected = [ + (1, 'def', 1, 0), + (1, 'f', 1, 4), + (7, '(', 1, 5), +@@ -293,8 +291,25 @@ class RoundtripLegalSyntaxTestCase(unittest.TestCase): + (4, '', 2, 16), + (6, '', 2, -1), + (4, '', 2, -1), +- (0, '', 2, -1)], +- terminals) ++ (0, '', 2, -1), ++ ] ++ ++ self.assertEqual(list(walk(st.totuple(line_info=True, col_info=True))), ++ expected) ++ self.assertEqual(list(walk(st.totuple())), ++ [(t, n) for t, n, l, c in expected]) ++ self.assertEqual(list(walk(st.totuple(line_info=True))), ++ [(t, n, l) for t, n, l, c in expected]) ++ self.assertEqual(list(walk(st.totuple(col_info=True))), ++ [(t, n, c) for t, n, l, c in expected]) ++ self.assertEqual(list(walk(st.tolist(line_info=True, col_info=True))), ++ [list(x) for x in expected]) ++ self.assertEqual(list(walk(parser.st2tuple(st, line_info=True, ++ col_info=True))), ++ expected) ++ self.assertEqual(list(walk(parser.st2list(st, line_info=True, ++ col_info=True))), ++ [list(x) for x in expected]) + + + # +diff --git a/Lib/test/test_pkg.py b/Lib/test/test_pkg.py +index 5f1659b0f6..ff05dce683 100644 +--- a/Lib/test/test_pkg.py ++++ b/Lib/test/test_pkg.py +@@ -134,7 +134,7 @@ class Test(unittest.TestCase): + + s = """ + from t2 import * +- self.assertTrue(dir(), ['self', 'sub']) ++ self.assertEqual(dir(), ['self', 'sub']) + """ + self.run_code(s) + +diff --git a/Lib/test/test_platform.py b/Lib/test/test_platform.py +index f754550f95..542763d46d 100644 +--- a/Lib/test/test_platform.py ++++ b/Lib/test/test_platform.py +@@ -4,7 +4,7 @@ import unittest + import platform + import subprocess + +-from test import test_support ++from test import support + + class PlatformTest(unittest.TestCase): + def test_architecture(self): +@@ -18,7 +18,7 @@ class PlatformTest(unittest.TestCase): + p = subprocess.Popen(cmd, stdout=subprocess.PIPE) + return p.communicate() + real = os.path.realpath(sys.executable) +- link = os.path.abspath(test_support.TESTFN) ++ link = os.path.abspath(support.TESTFN) + os.symlink(real, link) + try: + self.assertEqual(get(real), get(link)) +@@ -163,7 +163,7 @@ class PlatformTest(unittest.TestCase): + # using it, per + # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx + try: +- with test_support.EnvironmentVarGuard() as environ: ++ with support.EnvironmentVarGuard() as environ: + if 'PROCESSOR_ARCHITEW6432' in environ: + del environ['PROCESSOR_ARCHITEW6432'] + environ['PROCESSOR_ARCHITECTURE'] = 'foo' +@@ -247,7 +247,6 @@ class PlatformTest(unittest.TestCase): + res = platform.dist() + + def test_libc_ver(self): +- import os + if os.path.isdir(sys.executable) and \ + os.path.exists(sys.executable+'.exe'): + # Cygwin horror +@@ -256,6 +255,13 @@ class PlatformTest(unittest.TestCase): + executable = sys.executable + res = platform.libc_ver(executable) + ++ self.addCleanup(support.unlink, support.TESTFN) ++ with open(support.TESTFN, 'wb') as f: ++ f.write(b'x'*(16384-10)) ++ f.write(b'GLIBC_1.23.4\0GLIBC_1.9\0GLIBC_1.21\0') ++ self.assertEqual(platform.libc_ver(support.TESTFN), ++ ('glibc', '1.23.4')) ++ + def test_parse_release_file(self): + + for input, output in ( +@@ -275,7 +281,7 @@ class PlatformTest(unittest.TestCase): + + + def test_main(): +- test_support.run_unittest( ++ support.run_unittest( + PlatformTest + ) + +diff --git a/Lib/test/test_posix.py b/Lib/test/test_posix.py +index bce4e21e99..c4283b604b 100644 +--- a/Lib/test/test_posix.py ++++ b/Lib/test/test_posix.py +@@ -199,6 +199,7 @@ class PosixTester(unittest.TestCase): + def test_fdopen_directory(self): + try: + fd = os.open('.', os.O_RDONLY) ++ self.addCleanup(os.close, fd) + except OSError as e: + self.assertEqual(e.errno, errno.EACCES) + self.skipTest("system cannot open directories") +diff --git a/Lib/test/test_pty.py b/Lib/test/test_pty.py +index f623aa0962..0eb31fdaf7 100644 +--- a/Lib/test/test_pty.py ++++ b/Lib/test/test_pty.py +@@ -70,14 +70,11 @@ class PtyTest(unittest.TestCase): + def setUp(self): + # isatty() and close() can hang on some platforms. Set an alarm + # before running the test to make sure we don't hang forever. +- self.old_alarm = signal.signal(signal.SIGALRM, self.handle_sig) ++ old_alarm = signal.signal(signal.SIGALRM, self.handle_sig) ++ self.addCleanup(signal.signal, signal.SIGALRM, old_alarm) ++ self.addCleanup(signal.alarm, 0) + signal.alarm(10) + +- def tearDown(self): +- # remove alarm, restore old alarm handler +- signal.alarm(0) +- signal.signal(signal.SIGALRM, self.old_alarm) +- + def handle_sig(self, sig, frame): + self.fail("isatty hung") + +diff --git a/Lib/test/test_regrtest.py b/Lib/test/test_regrtest.py +index 988a72c109..a459504e44 100644 +--- a/Lib/test/test_regrtest.py ++++ b/Lib/test/test_regrtest.py +@@ -17,6 +17,8 @@ import tempfile + import textwrap + import unittest + from test import support ++# Use utils alias to use the same code for TestUtils in master and 2.7 branches ++import regrtest as utils + + + Py_DEBUG = hasattr(sys, 'getobjects') +@@ -92,6 +94,7 @@ class BaseTestCase(unittest.TestCase): + + def check_executed_tests(self, output, tests, skipped=(), failed=(), + env_changed=(), omitted=(), ++ rerun=(), + randomize=False, interrupted=False, + fail_env_changed=False): + if isinstance(tests, str): +@@ -104,6 +107,8 @@ class BaseTestCase(unittest.TestCase): + env_changed = [env_changed] + if isinstance(omitted, str): + omitted = [omitted] ++ if isinstance(rerun, str): ++ rerun = [rerun] + + executed = self.parse_executed_tests(output) + if randomize: +@@ -138,6 +143,14 @@ class BaseTestCase(unittest.TestCase): + regex = list_regex('%s test%s omitted', omitted) + self.check_line(output, regex) + ++ if rerun: ++ regex = list_regex('%s re-run test%s', rerun) ++ self.check_line(output, regex) ++ self.check_line(output, "Re-running failed tests in verbose mode") ++ for name in rerun: ++ regex = "Re-running test %r in verbose mode" % name ++ self.check_line(output, regex) ++ + good = (len(tests) - len(skipped) - len(failed) + - len(omitted) - len(env_changed)) + if good: +@@ -149,14 +162,19 @@ class BaseTestCase(unittest.TestCase): + if interrupted: + self.check_line(output, 'Test suite interrupted by signal SIGINT.') + ++ result = [] + if failed: +- result = 'FAILURE' +- elif interrupted: +- result = 'INTERRUPTED' ++ result.append('FAILURE') + elif fail_env_changed and env_changed: +- result = 'ENV CHANGED' +- else: +- result = 'SUCCESS' ++ result.append('ENV CHANGED') ++ if interrupted: ++ result.append('INTERRUPTED') ++ if not result: ++ result.append('SUCCESS') ++ result = ', '.join(result) ++ if rerun: ++ self.check_line(output, 'Tests result: %s' % result) ++ result = 'FAILURE then %s' % result + self.check_line(output, 'Tests result: %s' % result) + + def parse_random_seed(self, output): +@@ -511,6 +529,24 @@ class ArgsTestCase(BaseTestCase): + """) + self.check_leak(code, 'references') + ++ @unittest.skipUnless(Py_DEBUG, 'need a debug build') ++ def test_huntrleaks_fd_leak(self): ++ # test --huntrleaks for file descriptor leak ++ code = textwrap.dedent(""" ++ import os ++ import unittest ++ from test import support ++ ++ class FDLeakTest(unittest.TestCase): ++ def test_leak(self): ++ fd = os.open(__file__, os.O_RDONLY) ++ # bug: never close the file descriptor ++ ++ def test_main(): ++ support.run_unittest(FDLeakTest) ++ """) ++ self.check_leak(code, 'file descriptors') ++ + def test_list_tests(self): + # test --list-tests + tests = [self.create_test() for i in range(5)] +@@ -630,9 +666,51 @@ class ArgsTestCase(BaseTestCase): + self.check_executed_tests(output, [testname], env_changed=testname, + fail_env_changed=True) + ++ def test_rerun_fail(self): ++ code = textwrap.dedent(""" ++ import unittest ++ ++ class Tests(unittest.TestCase): ++ def test_bug(self): ++ # test always fail ++ self.fail("bug") ++ ++ def test_main(): ++ support.run_unittest(Tests) ++ """) ++ testname = self.create_test(code=code) ++ ++ output = self.run_tests("-w", testname, exitcode=2) ++ self.check_executed_tests(output, [testname], ++ failed=testname, rerun=testname) ++ ++ ++class TestUtils(unittest.TestCase): ++ def test_format_duration(self): ++ self.assertEqual(utils.format_duration(0), ++ '0 ms') ++ self.assertEqual(utils.format_duration(1e-9), ++ '1 ms') ++ self.assertEqual(utils.format_duration(10e-3), ++ '10 ms') ++ self.assertEqual(utils.format_duration(1.5), ++ '1 sec 500 ms') ++ self.assertEqual(utils.format_duration(1), ++ '1 sec') ++ self.assertEqual(utils.format_duration(2 * 60), ++ '2 min') ++ self.assertEqual(utils.format_duration(2 * 60 + 1), ++ '2 min 1 sec') ++ self.assertEqual(utils.format_duration(3 * 3600), ++ '3 hour') ++ self.assertEqual(utils.format_duration(3 * 3600 + 2 * 60 + 1), ++ '3 hour 2 min') ++ self.assertEqual(utils.format_duration(3 * 3600 + 1), ++ '3 hour 1 sec') ++ + + def test_main(): +- support.run_unittest(ProgramsTestCase, ArgsTestCase) ++ support.run_unittest(ProgramsTestCase, ArgsTestCase, TestUtils) + + + if __name__ == "__main__": +diff --git a/Lib/test/test_robotparser.py b/Lib/test/test_robotparser.py +index 8ed5d89036..ba7ccf8b58 100644 +--- a/Lib/test/test_robotparser.py ++++ b/Lib/test/test_robotparser.py +@@ -136,6 +136,31 @@ Disallow: /cyberworld/map/ + bad = ['/cyberworld/map/index.html'] + + ++class StringFormattingTest(BaseRobotTest, unittest.TestCase): ++ robots_txt = """\ ++User-agent: * ++Crawl-delay: 1 ++Request-rate: 3/15 ++Disallow: /cyberworld/map/ # This is an infinite virtual URL space ++ ++# Cybermapper knows where to go. ++User-agent: cybermapper ++Disallow: /some/path ++ """ ++ ++ expected_output = """\ ++User-agent: cybermapper ++Disallow: /some/path ++ ++User-agent: * ++Disallow: /cyberworld/map/ ++ ++""" ++ ++ def test_string_formatting(self): ++ self.assertEqual(str(self.parser), self.expected_output) ++ ++ + class RobotHandler(BaseHTTPRequestHandler): + + def do_GET(self): +@@ -226,6 +251,7 @@ def test_main(): + UseFirstUserAgentWildcardTest, + EmptyQueryStringTest, + DefaultEntryTest, ++ StringFormattingTest, + PasswordProtectedSiteTestCase, + NetworkTestCase) + +diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py +index 8338712da2..ca89fe509b 100644 +--- a/Lib/test/test_shutil.py ++++ b/Lib/test/test_shutil.py +@@ -543,6 +543,8 @@ class TestShutil(unittest.TestCase): + subprocess.check_output(zip_cmd, stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as exc: + details = exc.output ++ if 'unrecognized option: t' in details: ++ self.skipTest("unzip doesn't support -t") + msg = "{}\n\n**Unzip Output**\n{}" + self.fail(msg.format(exc, details)) + +diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py +index 5cff13a0df..5f4f579a67 100644 +--- a/Lib/test/test_signal.py ++++ b/Lib/test/test_signal.py +@@ -138,6 +138,8 @@ class InterProcessSignalTests(unittest.TestCase): + else: + self.fail("pause returned of its own accord, and the signal" + " didn't arrive after another second.") ++ finally: ++ signal.alarm(0) + + # Issue 3864. Unknown if this affects earlier versions of freebsd also. + @unittest.skipIf(sys.platform=='freebsd6', +@@ -246,11 +248,15 @@ class WakeupSignalTests(unittest.TestCase): + import select + + signal.alarm(1) +- before_time = time.time() +- # We attempt to get a signal during the sleep, +- # before select is called +- time.sleep(self.TIMEOUT_FULL) +- mid_time = time.time() ++ try: ++ before_time = time.time() ++ # We attempt to get a signal during the sleep, ++ # before select is called ++ time.sleep(self.TIMEOUT_FULL) ++ mid_time = time.time() ++ finally: ++ signal.alarm(0) ++ + self.assertTrue(mid_time - before_time < self.TIMEOUT_HALF) + select.select([self.read], [], [], self.TIMEOUT_FULL) + after_time = time.time() +@@ -260,11 +266,15 @@ class WakeupSignalTests(unittest.TestCase): + import select + + signal.alarm(1) +- before_time = time.time() +- # We attempt to get a signal during the select call +- self.assertRaises(select.error, select.select, +- [self.read], [], [], self.TIMEOUT_FULL) +- after_time = time.time() ++ try: ++ before_time = time.time() ++ # We attempt to get a signal during the select call ++ self.assertRaises(select.error, select.select, ++ [self.read], [], [], self.TIMEOUT_FULL) ++ after_time = time.time() ++ finally: ++ signal.alarm(0) ++ + self.assertTrue(after_time - before_time < self.TIMEOUT_HALF) + + def setUp(self): +diff --git a/Lib/test/test_smtplib.py b/Lib/test/test_smtplib.py +index 1bb6690188..703b631c17 100644 +--- a/Lib/test/test_smtplib.py ++++ b/Lib/test/test_smtplib.py +@@ -306,12 +306,14 @@ class TooLongLineTests(unittest.TestCase): + self.sock.settimeout(15) + self.port = test_support.bind_port(self.sock) + servargs = (self.evt, self.respdata, self.sock) +- threading.Thread(target=server, args=servargs).start() ++ self.thread = threading.Thread(target=server, args=servargs) ++ self.thread.start() + self.evt.wait() + self.evt.clear() + + def tearDown(self): + self.evt.wait() ++ self.thread.join() + sys.stdout = self.old_stdout + + def testLineTooLong(self): +diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py +index ca53899418..1460711592 100644 +--- a/Lib/test/test_socket.py ++++ b/Lib/test/test_socket.py +@@ -1534,8 +1534,8 @@ class TCPTimeoutTest(SocketTCPTest): + raise Alarm + old_alarm = signal.signal(signal.SIGALRM, alarm_handler) + try: +- signal.alarm(2) # POSIX allows alarm to be up to 1 second early + try: ++ signal.alarm(2) # POSIX allows alarm to be up to 1 second early + foo = self.serv.accept() + except socket.timeout: + self.fail("caught timeout instead of Alarm") +diff --git a/Lib/test/test_socketserver.py b/Lib/test/test_socketserver.py +index 0087b9e24d..847859d06b 100644 +--- a/Lib/test/test_socketserver.py ++++ b/Lib/test/test_socketserver.py +@@ -88,12 +88,13 @@ class SocketServerTest(unittest.TestCase): + """Test all socket servers.""" + + def setUp(self): ++ self.addCleanup(signal_alarm, 0) + signal_alarm(60) # Kill deadlocks after 60 seconds. + self.port_seed = 0 + self.test_files = [] + + def tearDown(self): +- signal_alarm(0) # Didn't deadlock. ++ self.doCleanups() + reap_children() + + for fn in self.test_files: +diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py +index b59fe73f04..dc14e22ad1 100644 +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -73,7 +73,7 @@ BADKEY = data_file("badkey.pem") + NOKIACERT = data_file("nokia.pem") + NULLBYTECERT = data_file("nullbytecert.pem") + +-DHFILE = data_file("dh1024.pem") ++DHFILE = data_file("ffdh3072.pem") + BYTES_DHFILE = DHFILE.encode(sys.getfilesystemencoding()) + + +@@ -201,9 +201,9 @@ class BasicSocketTests(unittest.TestCase): + (('commonName', 'localhost'),)) + ) + # Note the next three asserts will fail if the keys are regenerated +- self.assertEqual(p['notAfter'], asn1time('Oct 5 23:01:56 2020 GMT')) +- self.assertEqual(p['notBefore'], asn1time('Oct 8 23:01:56 2010 GMT')) +- self.assertEqual(p['serialNumber'], 'D7C7381919AFC24E') ++ self.assertEqual(p['notAfter'], asn1time('Aug 26 14:23:15 2028 GMT')) ++ self.assertEqual(p['notBefore'], asn1time('Aug 29 14:23:15 2018 GMT')) ++ self.assertEqual(p['serialNumber'], '98A7CF88C74A32ED') + self.assertEqual(p['subject'], + ((('countryName', 'XY'),), + (('localityName', 'Castle Anthrax'),), +@@ -989,6 +989,13 @@ class ContextTests(unittest.TestCase): + + + def test_load_dh_params(self): ++ filename = u'dhpäräm.pem' ++ fs_encoding = sys.getfilesystemencoding() ++ try: ++ filename.encode(fs_encoding) ++ except UnicodeEncodeError: ++ self.skipTest("filename %r cannot be encoded to the filesystem encoding %r" % (filename, fs_encoding)) ++ + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx.load_dh_params(DHFILE) + if os.name != 'nt': +@@ -1001,7 +1008,7 @@ class ContextTests(unittest.TestCase): + with self.assertRaises(ssl.SSLError) as cm: + ctx.load_dh_params(CERTFILE) + with support.temp_dir() as d: +- fname = os.path.join(d, u'dhpäräm.pem') ++ fname = os.path.join(d, filename) + shutil.copy(DHFILE, fname) + ctx.load_dh_params(fname) + +@@ -2204,10 +2211,10 @@ else: + connect to it with a wrong client certificate fails. + """ + certfile = os.path.join(os.path.dirname(__file__) or os.curdir, +- "wrongcert.pem") +- server = ThreadedEchoServer(CERTFILE, ++ "keycert.pem") ++ server = ThreadedEchoServer(SIGNED_CERTFILE, + certreqs=ssl.CERT_REQUIRED, +- cacerts=CERTFILE, chatty=False, ++ cacerts=SIGNING_CA, chatty=False, + connectionchatty=False) + with server, \ + closing(socket.socket()) as sock, \ +diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py +index ee2383b8a9..0c215f75e0 100644 +--- a/Lib/test/test_subprocess.py ++++ b/Lib/test/test_subprocess.py +@@ -843,8 +843,11 @@ class _SuppressCoreFiles(object): + kw = {stream: subprocess.PIPE} + with subprocess.Popen(args, **kw) as process: + signal.alarm(1) +- # communicate() will be interrupted by SIGALRM +- process.communicate() ++ try: ++ # communicate() will be interrupted by SIGALRM ++ process.communicate() ++ finally: ++ signal.alarm(0) + + + @unittest.skipIf(mswindows, "POSIX specific tests") +diff --git a/Lib/test/test_sundry.py b/Lib/test/test_sundry.py +index 8fe89953b7..d4a97c82d9 100644 +--- a/Lib/test/test_sundry.py ++++ b/Lib/test/test_sundry.py +@@ -10,7 +10,6 @@ class TestUntestedModules(unittest.TestCase): + with test_support.check_warnings(quiet=True): + import CGIHTTPServer + import audiodev +- import bdb + import cgitb + import code + import compileall +diff --git a/Lib/test/test_tcl.py b/Lib/test/test_tcl.py +index f0c9877862..84c4ceab00 100644 +--- a/Lib/test/test_tcl.py ++++ b/Lib/test/test_tcl.py +@@ -661,6 +661,43 @@ class TclTest(unittest.TestCase): + expected = {'a': (1, 2, 3), 'something': 'foo', 'status': ''} + self.assertEqual(splitdict(tcl, arg), expected) + ++ def test_join(self): ++ join = tkinter._join ++ tcl = self.interp.tk ++ def unpack(s): ++ return tcl.call('lindex', s, 0) ++ def check(value): ++ self.assertEqual(unpack(join([value])), value) ++ self.assertEqual(unpack(join([value, 0])), value) ++ self.assertEqual(unpack(unpack(join([[value]]))), value) ++ self.assertEqual(unpack(unpack(join([[value, 0]]))), value) ++ self.assertEqual(unpack(unpack(join([[value], 0]))), value) ++ self.assertEqual(unpack(unpack(join([[value, 0], 0]))), value) ++ check('') ++ check('spam') ++ check('sp am') ++ check('sp\tam') ++ check('sp\nam') ++ check(' \t\n') ++ check('{spam}') ++ check('{sp am}') ++ check('"spam"') ++ check('"sp am"') ++ check('{"spam"}') ++ check('"{spam}"') ++ check('sp\\am') ++ check('"sp\\am"') ++ check('"{}" "{}"') ++ check('"\\') ++ check('"{') ++ check('"}') ++ check('\n\\') ++ check('\n{') ++ check('\n}') ++ check('\\\n') ++ check('{\n') ++ check('}\n') ++ + + character_size = 4 if sys.maxunicode > 0xFFFF else 2 + +diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py +index 5c111a29ca..2efb8362fe 100644 +--- a/Lib/test/test_tempfile.py ++++ b/Lib/test/test_tempfile.py +@@ -821,6 +821,7 @@ class test_NamedTemporaryFile(TC): + old_fdopen = os.fdopen + closed = [] + def close(fd): ++ old_close(fd) + closed.append(fd) + def fdopen(*args): + raise ValueError() +diff --git a/Lib/test/test_test_support.py b/Lib/test/test_test_support.py +index 421a9ef889..f9192a7c1f 100644 +--- a/Lib/test/test_test_support.py ++++ b/Lib/test/test_test_support.py +@@ -267,7 +267,7 @@ class TestSupport(unittest.TestCase): + with support.temp_cwd(name=TESTFN): + self.assertEqual(os.path.basename(os.getcwd()), TESTFN) + self.assertFalse(os.path.exists(TESTFN)) +- self.assertTrue(os.path.basename(os.getcwd()), here) ++ self.assertEqual(os.getcwd(), here) + + + def test_temp_cwd__name_none(self): +@@ -417,6 +417,17 @@ class TestSupport(unittest.TestCase): + self.assertTrue(support.match_test(test_access)) + self.assertFalse(support.match_test(test_chdir)) + ++ def test_fd_count(self): ++ # We cannot test the absolute value of fd_count(): on old Linux ++ # kernel or glibc versions, os.urandom() keeps a FD open on ++ # /dev/urandom device and Python has 4 FD opens instead of 3. ++ start = support.fd_count() ++ fd = os.open(__file__, os.O_RDONLY) ++ try: ++ more = support.fd_count() ++ finally: ++ os.close(fd) ++ self.assertEqual(more - start, 1) + + # XXX -follows a list of untested API + # make_legacy_pyc +diff --git a/Lib/test/test_thread.py b/Lib/test/test_thread.py +index c8caa5ddff..93690a60b2 100644 +--- a/Lib/test/test_thread.py ++++ b/Lib/test/test_thread.py +@@ -1,8 +1,8 @@ + import os + import unittest + import random +-from test import test_support +-thread = test_support.import_module('thread') ++from test import support ++thread = support.import_module('thread') + import time + import sys + import weakref +@@ -17,7 +17,7 @@ _print_mutex = thread.allocate_lock() + + def verbose_print(arg): + """Helper function for printing out debugging output.""" +- if test_support.verbose: ++ if support.verbose: + with _print_mutex: + print arg + +@@ -34,8 +34,8 @@ class BasicThreadTest(unittest.TestCase): + self.running = 0 + self.next_ident = 0 + +- key = test_support.threading_setup() +- self.addCleanup(test_support.threading_cleanup, *key) ++ key = support.threading_setup() ++ self.addCleanup(support.threading_cleanup, *key) + + + class ThreadRunningTests(BasicThreadTest): +@@ -60,12 +60,13 @@ class ThreadRunningTests(BasicThreadTest): + self.done_mutex.release() + + def test_starting_threads(self): +- # Basic test for thread creation. +- for i in range(NUMTASKS): +- self.newtask() +- verbose_print("waiting for tasks to complete...") +- self.done_mutex.acquire() +- verbose_print("all tasks done") ++ with support.wait_threads_exit(): ++ # Basic test for thread creation. ++ for i in range(NUMTASKS): ++ self.newtask() ++ verbose_print("waiting for tasks to complete...") ++ self.done_mutex.acquire() ++ verbose_print("all tasks done") + + def test_stack_size(self): + # Various stack size tests. +@@ -95,12 +96,13 @@ class ThreadRunningTests(BasicThreadTest): + verbose_print("trying stack_size = (%d)" % tss) + self.next_ident = 0 + self.created = 0 +- for i in range(NUMTASKS): +- self.newtask() ++ with support.wait_threads_exit(): ++ for i in range(NUMTASKS): ++ self.newtask() + +- verbose_print("waiting for all tasks to complete") +- self.done_mutex.acquire() +- verbose_print("all tasks done") ++ verbose_print("waiting for all tasks to complete") ++ self.done_mutex.acquire() ++ verbose_print("all tasks done") + + thread.stack_size(0) + +@@ -110,25 +112,28 @@ class ThreadRunningTests(BasicThreadTest): + mut = thread.allocate_lock() + mut.acquire() + started = [] ++ + def task(): + started.append(None) + mut.acquire() + mut.release() +- thread.start_new_thread(task, ()) +- while not started: +- time.sleep(0.01) +- self.assertEqual(thread._count(), orig + 1) +- # Allow the task to finish. +- mut.release() +- # The only reliable way to be sure that the thread ended from the +- # interpreter's point of view is to wait for the function object to be +- # destroyed. +- done = [] +- wr = weakref.ref(task, lambda _: done.append(None)) +- del task +- while not done: +- time.sleep(0.01) +- self.assertEqual(thread._count(), orig) ++ ++ with support.wait_threads_exit(): ++ thread.start_new_thread(task, ()) ++ while not started: ++ time.sleep(0.01) ++ self.assertEqual(thread._count(), orig + 1) ++ # Allow the task to finish. ++ mut.release() ++ # The only reliable way to be sure that the thread ended from the ++ # interpreter's point of view is to wait for the function object to be ++ # destroyed. ++ done = [] ++ wr = weakref.ref(task, lambda _: done.append(None)) ++ del task ++ while not done: ++ time.sleep(0.01) ++ self.assertEqual(thread._count(), orig) + + def test_save_exception_state_on_error(self): + # See issue #14474 +@@ -143,14 +148,13 @@ class ThreadRunningTests(BasicThreadTest): + real_write(self, *args) + c = thread._count() + started = thread.allocate_lock() +- with test_support.captured_output("stderr") as stderr: ++ with support.captured_output("stderr") as stderr: + real_write = stderr.write + stderr.write = mywrite + started.acquire() +- thread.start_new_thread(task, ()) +- started.acquire() +- while thread._count() > c: +- time.sleep(0.01) ++ with support.wait_threads_exit(): ++ thread.start_new_thread(task, ()) ++ started.acquire() + self.assertIn("Traceback", stderr.getvalue()) + + +@@ -182,13 +186,14 @@ class Barrier: + class BarrierTest(BasicThreadTest): + + def test_barrier(self): +- self.bar = Barrier(NUMTASKS) +- self.running = NUMTASKS +- for i in range(NUMTASKS): +- thread.start_new_thread(self.task2, (i,)) +- verbose_print("waiting for tasks to end") +- self.done_mutex.acquire() +- verbose_print("tasks done") ++ with support.wait_threads_exit(): ++ self.bar = Barrier(NUMTASKS) ++ self.running = NUMTASKS ++ for i in range(NUMTASKS): ++ thread.start_new_thread(self.task2, (i,)) ++ verbose_print("waiting for tasks to end") ++ self.done_mutex.acquire() ++ verbose_print("tasks done") + + def task2(self, ident): + for i in range(NUMTRIPS): +@@ -226,8 +231,9 @@ class TestForkInThread(unittest.TestCase): + + @unittest.skipIf(sys.platform.startswith('win'), + "This test is only appropriate for POSIX-like systems.") +- @test_support.reap_threads ++ @support.reap_threads + def test_forkinthread(self): ++ non_local = {'status': None} + def thread1(): + try: + pid = os.fork() # fork in a thread +@@ -246,11 +252,13 @@ class TestForkInThread(unittest.TestCase): + else: # parent + os.close(self.write_fd) + pid, status = os.waitpid(pid, 0) +- self.assertEqual(status, 0) ++ non_local['status'] = status + +- thread.start_new_thread(thread1, ()) +- self.assertEqual(os.read(self.read_fd, 2), "OK", +- "Unable to fork() in thread") ++ with support.wait_threads_exit(): ++ thread.start_new_thread(thread1, ()) ++ self.assertEqual(os.read(self.read_fd, 2), "OK", ++ "Unable to fork() in thread") ++ self.assertEqual(non_local['status'], 0) + + def tearDown(self): + try: +@@ -265,7 +273,7 @@ class TestForkInThread(unittest.TestCase): + + + def test_main(): +- test_support.run_unittest(ThreadRunningTests, BarrierTest, LockTests, ++ support.run_unittest(ThreadRunningTests, BarrierTest, LockTests, + TestForkInThread) + + if __name__ == "__main__": +diff --git a/Lib/test/test_threadsignals.py b/Lib/test/test_threadsignals.py +index 2f7eb607c7..3d79fd508e 100644 +--- a/Lib/test/test_threadsignals.py ++++ b/Lib/test/test_threadsignals.py +@@ -52,9 +52,11 @@ class ThreadSignals(unittest.TestCase): + # wait for it return. + if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \ + or signal_blackboard[signal.SIGUSR2]['tripped'] == 0: +- signal.alarm(1) +- signal.pause() +- signal.alarm(0) ++ try: ++ signal.alarm(1) ++ signal.pause() ++ finally: ++ signal.alarm(0) + + self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1) + self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'], +diff --git a/Lib/test/test_tokenize.py b/Lib/test/test_tokenize.py +index fd9486bdd7..a4625971d3 100644 +--- a/Lib/test/test_tokenize.py ++++ b/Lib/test/test_tokenize.py +@@ -1,32 +1,54 @@ + from test import test_support +-from tokenize import (untokenize, generate_tokens, NUMBER, NAME, OP, ++from tokenize import (untokenize, generate_tokens, NUMBER, NAME, OP, NEWLINE, + STRING, ENDMARKER, tok_name, Untokenizer, tokenize) + from StringIO import StringIO + import os + from unittest import TestCase + + ++# Converts a source string into a list of textual representation ++# of the tokens such as: ++# ` NAME 'if' (1, 0) (1, 2)` ++# to make writing tests easier. ++def stringify_tokens_from_source(token_generator, source_string): ++ result = [] ++ num_lines = len(source_string.splitlines()) ++ missing_trailing_nl = source_string[-1] not in '\r\n' ++ ++ for type, token, start, end, line in token_generator: ++ if type == ENDMARKER: ++ break ++ # Ignore the new line on the last line if the input lacks one ++ if missing_trailing_nl and type == NEWLINE and end[0] == num_lines: ++ continue ++ type = tok_name[type] ++ result.append(" %(type)-10.10s %(token)-13.13r %(start)s %(end)s" % ++ locals()) ++ ++ return result ++ + class TokenizeTest(TestCase): + # Tests for the tokenize module. + + # The tests can be really simple. Given a small fragment of source +- # code, print out a table with tokens. The ENDMARKER is omitted for +- # brevity. ++ # code, print out a table with tokens. The ENDMARKER, ENCODING and ++ # final NEWLINE are omitted for brevity. + + def check_tokenize(self, s, expected): + # Format the tokens in s in a table format. +- # The ENDMARKER is omitted. +- result = [] + f = StringIO(s) +- for type, token, start, end, line in generate_tokens(f.readline): +- if type == ENDMARKER: +- break +- type = tok_name[type] +- result.append(" %(type)-10.10s %(token)-13.13r %(start)s %(end)s" % +- locals()) ++ result = stringify_tokens_from_source(generate_tokens(f.readline), s) ++ + self.assertEqual(result, + expected.rstrip().splitlines()) + ++ def test_implicit_newline(self): ++ # Make sure that the tokenizer puts in an implicit NEWLINE ++ # when the input lacks a trailing new line. ++ f = StringIO("x") ++ tokens = list(generate_tokens(f.readline)) ++ self.assertEqual(tokens[-2][0], NEWLINE) ++ self.assertEqual(tokens[-1][0], ENDMARKER) + + def test_basic(self): + self.check_tokenize("1 + 1", """\ +@@ -616,7 +638,7 @@ class TestRoundtrip(TestCase): + self.check_roundtrip("if x == 1:\n" + " print x\n") + self.check_roundtrip("# This is a comment\n" +- "# This also") ++ "# This also\n") + + # Some people use different formatting conventions, which makes + # untokenize a little trickier. Note that this test involves trailing +diff --git a/Lib/test/test_tools.py b/Lib/test/test_tools.py +index 57b3ef11fd..51e4fd61c7 100644 +--- a/Lib/test/test_tools.py ++++ b/Lib/test/test_tools.py +@@ -416,12 +416,15 @@ class FixcidTests(unittest.TestCase): + with open(os.path.join(test_support.TESTFN, "file.py"), "w") as file: + file.write("xx = 'unaltered'\n") + script = os.path.join(scriptsdir, "fixcid.py") +- output = self.run_script(args=(test_support.TESTFN,)) ++ # ignore dbg() messages ++ with test_support.captured_stderr() as stderr: ++ output = self.run_script(args=(test_support.TESTFN,)) + self.assertMultiLineEqual(output, + "{}:\n" + "1\n" + '< int xx;\n' +- '> int yy;\n'.format(c_filename) ++ '> int yy;\n'.format(c_filename), ++ "stderr: %s" % stderr.getvalue() + ) + + def run_script(self, input="", args=("-",), substfile="xx yy\n"): +diff --git a/Lib/test/test_unicodedata.py b/Lib/test/test_unicodedata.py +index c30ecf4c5b..11f2cda820 100644 +--- a/Lib/test/test_unicodedata.py ++++ b/Lib/test/test_unicodedata.py +@@ -204,6 +204,19 @@ class UnicodeFunctionsTest(UnicodeDatabaseTest): + b = u'C\u0338' * 20 + u'\xC7' + self.assertEqual(self.db.normalize('NFC', a), b) + ++ def test_issue29456(self): ++ # Fix #29456 ++ u1176_str_a = u'\u1100\u1176\u11a8' ++ u1176_str_b = u'\u1100\u1176\u11a8' ++ u11a7_str_a = u'\u1100\u1175\u11a7' ++ u11a7_str_b = u'\uae30\u11a7' ++ u11c3_str_a = u'\u1100\u1175\u11c3' ++ u11c3_str_b = u'\uae30\u11c3' ++ self.assertEqual(self.db.normalize('NFC', u1176_str_a), u1176_str_b) ++ self.assertEqual(self.db.normalize('NFC', u11a7_str_a), u11a7_str_b) ++ self.assertEqual(self.db.normalize('NFC', u11c3_str_a), u11c3_str_b) ++ ++ + def test_east_asian_width(self): + eaw = self.db.east_asian_width + self.assertRaises(TypeError, eaw, 'a') +diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py +index 89ee75919c..4ba79cbc31 100644 +--- a/Lib/test/test_urllib2net.py ++++ b/Lib/test/test_urllib2net.py +@@ -184,6 +184,7 @@ class OtherNetworkTests(unittest.TestCase): + opener.open(request) + self.assertEqual(request.get_header('User-agent'),'Test-Agent') + ++ @unittest.skip('XXX: http://www.imdb.com is gone') + def test_sites_no_connection_close(self): + # Some sites do not send Connection: close header. + # Verify that those work properly. (#issue12576) +diff --git a/Lib/test/test_uu.py b/Lib/test/test_uu.py +index 51a4fbeaf9..df41cbc12d 100644 +--- a/Lib/test/test_uu.py ++++ b/Lib/test/test_uu.py +@@ -4,9 +4,10 @@ Nick Mathewson + """ + + import unittest +-from test import test_support ++from test import test_support as support + +-import sys, os, uu, cStringIO ++import cStringIO ++import sys + import uu + + plaintext = "The smooth-scaled python crept over the sleeping dog\n" +@@ -108,114 +109,64 @@ class UUStdIOTest(unittest.TestCase): + + class UUFileTest(unittest.TestCase): + +- def _kill(self, f): +- # close and remove file +- try: +- f.close() +- except (SystemExit, KeyboardInterrupt): +- raise +- except: +- pass +- try: +- os.unlink(f.name) +- except (SystemExit, KeyboardInterrupt): +- raise +- except: +- pass +- + def setUp(self): +- self.tmpin = test_support.TESTFN + "i" +- self.tmpout = test_support.TESTFN + "o" +- +- def tearDown(self): +- del self.tmpin +- del self.tmpout ++ self.tmpin = support.TESTFN + "i" ++ self.tmpout = support.TESTFN + "o" ++ self.addCleanup(support.unlink, self.tmpin) ++ self.addCleanup(support.unlink, self.tmpout) + + def test_encode(self): +- fin = fout = None +- try: +- test_support.unlink(self.tmpin) +- fin = open(self.tmpin, 'wb') ++ with open(self.tmpin, 'wb') as fin: + fin.write(plaintext) +- fin.close() + +- fin = open(self.tmpin, 'rb') +- fout = open(self.tmpout, 'w') +- uu.encode(fin, fout, self.tmpin, mode=0644) +- fin.close() +- fout.close() ++ with open(self.tmpin, 'rb') as fin: ++ with open(self.tmpout, 'w') as fout: ++ uu.encode(fin, fout, self.tmpin, mode=0o644) + +- fout = open(self.tmpout, 'r') ++ with open(self.tmpout, 'r') as fout: + s = fout.read() +- fout.close() +- self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) ++ self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin)) + +- # in_file and out_file as filenames +- uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) +- fout = open(self.tmpout, 'r') ++ # in_file and out_file as filenames ++ uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644) ++ with open(self.tmpout, 'r') as fout: + s = fout.read() +- fout.close() +- self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) +- +- finally: +- self._kill(fin) +- self._kill(fout) ++ self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin)) + + def test_decode(self): +- f = None +- try: +- test_support.unlink(self.tmpin) +- f = open(self.tmpin, 'w') +- f.write(encodedtextwrapped % (0644, self.tmpout)) +- f.close() ++ with open(self.tmpin, 'w') as f: ++ f.write(encodedtextwrapped % (0o644, self.tmpout)) + +- f = open(self.tmpin, 'r') ++ with open(self.tmpin, 'r') as f: + uu.decode(f) +- f.close() + +- f = open(self.tmpout, 'r') ++ with open(self.tmpout, 'r') as f: + s = f.read() +- f.close() +- self.assertEqual(s, plaintext) +- # XXX is there an xp way to verify the mode? +- finally: +- self._kill(f) ++ self.assertEqual(s, plaintext) ++ # XXX is there an xp way to verify the mode? + + def test_decode_filename(self): +- f = None +- try: +- test_support.unlink(self.tmpin) +- f = open(self.tmpin, 'w') +- f.write(encodedtextwrapped % (0644, self.tmpout)) +- f.close() ++ with open(self.tmpin, 'w') as f: ++ f.write(encodedtextwrapped % (0o644, self.tmpout)) + +- uu.decode(self.tmpin) ++ uu.decode(self.tmpin) + +- f = open(self.tmpout, 'r') ++ with open(self.tmpout, 'r') as f: + s = f.read() +- f.close() +- self.assertEqual(s, plaintext) +- finally: +- self._kill(f) ++ self.assertEqual(s, plaintext) + + def test_decodetwice(self): + # Verify that decode() will refuse to overwrite an existing file +- f = None +- try: +- f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout)) +- +- f = open(self.tmpin, 'r') ++ with open(self.tmpin, 'wb') as f: ++ f.write(encodedtextwrapped % (0o644, self.tmpout)) ++ with open(self.tmpin, 'r') as f: + uu.decode(f) +- f.close() + +- f = open(self.tmpin, 'r') ++ with open(self.tmpin, 'r') as f: + self.assertRaises(uu.Error, uu.decode, f) +- f.close() +- finally: +- self._kill(f) + + def test_main(): +- test_support.run_unittest(UUTest, UUStdIOTest, UUFileTest) ++ support.run_unittest(UUTest, UUStdIOTest, UUFileTest) + + if __name__=="__main__": + test_main() +diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py +index 3749564c93..6cd2c39293 100644 +--- a/Lib/test/test_uuid.py ++++ b/Lib/test/test_uuid.py +@@ -287,6 +287,39 @@ class TestUUID(unittest.TestCase): + node2 = uuid.getnode() + self.assertEqual(node1, node2, '%012x != %012x' % (node1, node2)) + ++ # bpo-32502: UUID1 requires a 48-bit identifier, but hardware identifiers ++ # need not necessarily be 48 bits (e.g., EUI-64). ++ def test_uuid1_eui64(self): ++ # Confirm that uuid.getnode ignores hardware addresses larger than 48 ++ # bits. Mock out each platform's *_getnode helper functions to return ++ # something just larger than 48 bits to test. This will cause ++ # uuid.getnode to fall back on uuid._random_getnode, which will ++ # generate a valid value. ++ too_large_getter = lambda: 1 << 48 ++ ++ uuid_real__node = uuid._node ++ uuid_real__NODE_GETTERS_WIN32 = uuid._NODE_GETTERS_WIN32 ++ uuid_real__NODE_GETTERS_UNIX = uuid._NODE_GETTERS_UNIX ++ uuid._node = None ++ uuid._NODE_GETTERS_WIN32 = [too_large_getter] ++ uuid._NODE_GETTERS_UNIX = [too_large_getter] ++ try: ++ node = uuid.getnode() ++ finally: ++ uuid._node = uuid_real__node ++ uuid._NODE_GETTERS_WIN32 = uuid_real__NODE_GETTERS_WIN32 ++ uuid._NODE_GETTERS_UNIX = uuid_real__NODE_GETTERS_UNIX ++ ++ self.assertTrue(0 < node < (1 << 48), '%012x' % node) ++ ++ # Confirm that uuid1 can use the generated node, i.e., the that ++ # uuid.getnode fell back on uuid._random_getnode() rather than using ++ # the value from too_large_getter above. ++ try: ++ uuid.uuid1(node=node) ++ except ValueError as e: ++ self.fail('uuid1 was given an invalid node ID') ++ + @unittest.skipUnless(importable('ctypes'), 'requires ctypes') + def test_uuid1(self): + equal = self.assertEqual +diff --git a/Lib/test/test_warnings.py b/Lib/test/test_warnings.py +index ae081eeee3..a9568f64c5 100644 +--- a/Lib/test/test_warnings.py ++++ b/Lib/test/test_warnings.py +@@ -107,10 +107,14 @@ class FilterTests(object): + self.module.resetwarnings() + self.module.filterwarnings("always", category=UserWarning) + message = "FilterTests.test_always" +- self.module.warn(message, UserWarning) +- self.assertTrue(message, w[-1].message) +- self.module.warn(message, UserWarning) +- self.assertTrue(w[-1].message, message) ++ def f(): ++ self.module.warn(message, UserWarning) ++ f() ++ self.assertEqual(len(w), 1) ++ self.assertEqual(w[-1].message.args[0], message) ++ f() ++ self.assertEqual(len(w), 2) ++ self.assertEqual(w[-1].message.args[0], message) + + def test_default(self): + with original_warnings.catch_warnings(record=True, +diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py +index 97d9e8f789..36b3be67fd 100644 +--- a/Lib/test/test_xmlrpc.py ++++ b/Lib/test/test_xmlrpc.py +@@ -854,13 +854,9 @@ class GzipServerTestCase(BaseServerTestCase): + class ServerProxyTestCase(unittest.TestCase): + def setUp(self): + unittest.TestCase.setUp(self) +- if threading: +- self.url = URL +- else: +- # Without threading, http_server() and http_multi_server() will not +- # be executed and URL is still equal to None. 'http://' is a just +- # enough to choose the scheme (HTTP) +- self.url = 'http://' ++ # Actual value of the URL doesn't matter if it is a string in ++ # the correct format. ++ self.url = 'http://fake.localhost' + + def test_close(self): + p = xmlrpclib.ServerProxy(self.url) +diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py +index 9c63aebbbe..4e545f140a 100644 +--- a/Lib/test/test_zipfile.py ++++ b/Lib/test/test_zipfile.py +@@ -812,6 +812,20 @@ class TestZip64InSmallFiles(unittest.TestCase): + self.assertEqual(content, "%d" % (i**3 % 57)) + zipf2.close() + ++ def test_append(self): ++ # Test that appending to the Zip64 archive doesn't change ++ # extra fields of existing entries. ++ with zipfile.ZipFile(TESTFN2, "w", allowZip64=True) as zipfp: ++ zipfp.writestr("strfile", self.data) ++ with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp: ++ zinfo = zipfp.getinfo("strfile") ++ extra = zinfo.extra ++ with zipfile.ZipFile(TESTFN2, "a", allowZip64=True) as zipfp: ++ zipfp.writestr("strfile2", self.data) ++ with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp: ++ zinfo = zipfp.getinfo("strfile") ++ self.assertEqual(zinfo.extra, extra) ++ + def tearDown(self): + zipfile.ZIP64_LIMIT = self._limit + zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit +diff --git a/Lib/test/wrongcert.pem b/Lib/test/wrongcert.pem +deleted file mode 100644 +index 5f92f9bce7..0000000000 ++++ /dev/null +@@ -1,32 +0,0 @@ +------BEGIN RSA PRIVATE KEY----- +-MIICXAIBAAKBgQC89ZNxjTgWgq7Z1g0tJ65w+k7lNAj5IgjLb155UkUrz0XsHDnH +-FlbsVUg2Xtk6+bo2UEYIzN7cIm5ImpmyW/2z0J1IDVDlvR2xJ659xrE0v5c2cB6T +-f9lnNTwpSoeK24Nd7Jwq4j9vk95fLrdqsBq0/KVlsCXeixS/CaqqduXfvwIDAQAB +-AoGAQFko4uyCgzfxr4Ezb4Mp5pN3Npqny5+Jey3r8EjSAX9Ogn+CNYgoBcdtFgbq +-1yif/0sK7ohGBJU9FUCAwrqNBI9ZHB6rcy7dx+gULOmRBGckln1o5S1+smVdmOsW +-7zUVLBVByKuNWqTYFlzfVd6s4iiXtAE2iHn3GCyYdlICwrECQQDhMQVxHd3EFbzg +-SFmJBTARlZ2GKA3c1g/h9/XbkEPQ9/RwI3vnjJ2RaSnjlfoLl8TOcf0uOGbOEyFe +-19RvCLXjAkEA1s+UE5ziF+YVkW3WolDCQ2kQ5WG9+ccfNebfh6b67B7Ln5iG0Sbg +-ky9cjsO3jbMJQtlzAQnH1850oRD5Gi51dQJAIbHCDLDZU9Ok1TI+I2BhVuA6F666 +-lEZ7TeZaJSYq34OaUYUdrwG9OdqwZ9sy9LUav4ESzu2lhEQchCJrKMn23QJAReqs +-ZLHUeTjfXkVk7dHhWPWSlUZ6AhmIlA/AQ7Payg2/8wM/JkZEJEPvGVykms9iPUrv +-frADRr+hAGe43IewnQJBAJWKZllPgKuEBPwoEldHNS8nRu61D7HzxEzQ2xnfj+Nk +-2fgf1MAzzTRsikfGENhVsVWeqOcijWb6g5gsyCmlRpc= +------END RSA PRIVATE KEY----- +------BEGIN CERTIFICATE----- +-MIICsDCCAhmgAwIBAgIJAOqYOYFJfEEoMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +-BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX +-aWRnaXRzIFB0eSBMdGQwHhcNMDgwNjI2MTgxNTUyWhcNMDkwNjI2MTgxNTUyWjBF +-MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 +-ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB +-gQC89ZNxjTgWgq7Z1g0tJ65w+k7lNAj5IgjLb155UkUrz0XsHDnHFlbsVUg2Xtk6 +-+bo2UEYIzN7cIm5ImpmyW/2z0J1IDVDlvR2xJ659xrE0v5c2cB6Tf9lnNTwpSoeK +-24Nd7Jwq4j9vk95fLrdqsBq0/KVlsCXeixS/CaqqduXfvwIDAQABo4GnMIGkMB0G +-A1UdDgQWBBTctMtI3EO9OjLI0x9Zo2ifkwIiNjB1BgNVHSMEbjBsgBTctMtI3EO9 +-OjLI0x9Zo2ifkwIiNqFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUt +-U3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAOqYOYFJ +-fEEoMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAQwa7jya/DfhaDn7E +-usPkpgIX8WCL2B1SqnRTXEZfBPPVq/cUmFGyEVRVATySRuMwi8PXbVcOhXXuocA+ +-43W+iIsD9pXapCZhhOerCq18TC1dWK98vLUsoK8PMjB6e5H/O8bqojv0EeC+fyCw +-eSHj5jpC8iZKjCHBn+mAi4cQ514= +------END CERTIFICATE----- +diff --git a/Lib/tkinter/test/test_ttk/test_widgets.py b/Lib/tkinter/test/test_ttk/test_widgets.py +deleted file mode 100644 +index 5b0e29cdcc..0000000000 ++++ /dev/null +@@ -1,1872 +0,0 @@ +-import unittest +-import tkinter +-from tkinter import ttk, TclError +-from test.support import requires +-import sys +- +-from tkinter.test.test_ttk.test_functions import MockTclObj +-from tkinter.test.support import (AbstractTkTest, tcl_version, get_tk_patchlevel, +- simulate_mouse_click) +-from tkinter.test.widget_tests import (add_standard_options, noconv, +- AbstractWidgetTest, StandardOptionsTests, IntegerSizeTests, PixelSizeTests, +- setUpModule) +- +-requires('gui') +- +- +-class StandardTtkOptionsTests(StandardOptionsTests): +- +- def test_class(self): +- widget = self.create() +- self.assertEqual(widget['class'], '') +- errmsg='attempt to change read-only option' +- if get_tk_patchlevel() < (8, 6, 0, 'beta', 3): +- errmsg='Attempt to change read-only option' +- self.checkInvalidParam(widget, 'class', 'Foo', errmsg=errmsg) +- widget2 = self.create(class_='Foo') +- self.assertEqual(widget2['class'], 'Foo') +- +- def test_padding(self): +- widget = self.create() +- self.checkParam(widget, 'padding', 0, expected=('0',)) +- self.checkParam(widget, 'padding', 5, expected=('5',)) +- self.checkParam(widget, 'padding', (5, 6), expected=('5', '6')) +- self.checkParam(widget, 'padding', (5, 6, 7), +- expected=('5', '6', '7')) +- self.checkParam(widget, 'padding', (5, 6, 7, 8), +- expected=('5', '6', '7', '8')) +- self.checkParam(widget, 'padding', ('5p', '6p', '7p', '8p')) +- self.checkParam(widget, 'padding', (), expected='') +- +- def test_style(self): +- widget = self.create() +- self.assertEqual(widget['style'], '') +- errmsg = 'Layout Foo not found' +- if hasattr(self, 'default_orient'): +- errmsg = ('Layout %s.Foo not found' % +- getattr(self, 'default_orient').title()) +- self.checkInvalidParam(widget, 'style', 'Foo', +- errmsg=errmsg) +- widget2 = self.create(class_='Foo') +- self.assertEqual(widget2['class'], 'Foo') +- # XXX +- pass +- +- +-class WidgetTest(AbstractTkTest, unittest.TestCase): +- """Tests methods available in every ttk widget.""" +- +- def setUp(self): +- super().setUp() +- self.widget = ttk.Button(self.root, width=0, text="Text") +- self.widget.pack() +- self.widget.wait_visibility() +- +- +- def test_identify(self): +- self.widget.update_idletasks() +- self.assertEqual(self.widget.identify( +- int(self.widget.winfo_width() / 2), +- int(self.widget.winfo_height() / 2) +- ), "label") +- self.assertEqual(self.widget.identify(-1, -1), "") +- +- self.assertRaises(tkinter.TclError, self.widget.identify, None, 5) +- self.assertRaises(tkinter.TclError, self.widget.identify, 5, None) +- self.assertRaises(tkinter.TclError, self.widget.identify, 5, '') +- +- +- def test_widget_state(self): +- # XXX not sure about the portability of all these tests +- self.assertEqual(self.widget.state(), ()) +- self.assertEqual(self.widget.instate(['!disabled']), True) +- +- # changing from !disabled to disabled +- self.assertEqual(self.widget.state(['disabled']), ('!disabled', )) +- # no state change +- self.assertEqual(self.widget.state(['disabled']), ()) +- # change back to !disable but also active +- self.assertEqual(self.widget.state(['!disabled', 'active']), +- ('!active', 'disabled')) +- # no state changes, again +- self.assertEqual(self.widget.state(['!disabled', 'active']), ()) +- self.assertEqual(self.widget.state(['active', '!disabled']), ()) +- +- def test_cb(arg1, **kw): +- return arg1, kw +- self.assertEqual(self.widget.instate(['!disabled'], +- test_cb, "hi", **{"msg": "there"}), +- ('hi', {'msg': 'there'})) +- +- # attempt to set invalid statespec +- currstate = self.widget.state() +- self.assertRaises(tkinter.TclError, self.widget.instate, +- ['badstate']) +- self.assertRaises(tkinter.TclError, self.widget.instate, +- ['disabled', 'badstate']) +- # verify that widget didn't change its state +- self.assertEqual(currstate, self.widget.state()) +- +- # ensuring that passing None as state doesn't modify current state +- self.widget.state(['active', '!disabled']) +- self.assertEqual(self.widget.state(), ('active', )) +- +- +-class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests): +- _conv_pixels = noconv +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class FrameTest(AbstractToplevelTest, unittest.TestCase): +- OPTIONS = ( +- 'borderwidth', 'class', 'cursor', 'height', +- 'padding', 'relief', 'style', 'takefocus', +- 'width', +- ) +- +- def create(self, **kwargs): +- return ttk.Frame(self.root, **kwargs) +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class LabelFrameTest(AbstractToplevelTest, unittest.TestCase): +- OPTIONS = ( +- 'borderwidth', 'class', 'cursor', 'height', +- 'labelanchor', 'labelwidget', +- 'padding', 'relief', 'style', 'takefocus', +- 'text', 'underline', 'width', +- ) +- +- def create(self, **kwargs): +- return ttk.LabelFrame(self.root, **kwargs) +- +- def test_labelanchor(self): +- widget = self.create() +- self.checkEnumParam(widget, 'labelanchor', +- 'e', 'en', 'es', 'n', 'ne', 'nw', 's', 'se', 'sw', 'w', 'wn', 'ws', +- errmsg='Bad label anchor specification {}') +- self.checkInvalidParam(widget, 'labelanchor', 'center') +- +- def test_labelwidget(self): +- widget = self.create() +- label = ttk.Label(self.root, text='Mupp', name='foo') +- self.checkParam(widget, 'labelwidget', label, expected='.foo') +- label.destroy() +- +- +-class AbstractLabelTest(AbstractWidgetTest): +- +- def checkImageParam(self, widget, name): +- image = tkinter.PhotoImage(master=self.root, name='image1') +- image2 = tkinter.PhotoImage(master=self.root, name='image2') +- self.checkParam(widget, name, image, expected=('image1',)) +- self.checkParam(widget, name, 'image1', expected=('image1',)) +- self.checkParam(widget, name, (image,), expected=('image1',)) +- self.checkParam(widget, name, (image, 'active', image2), +- expected=('image1', 'active', 'image2')) +- self.checkParam(widget, name, 'image1 active image2', +- expected=('image1', 'active', 'image2')) +- self.checkInvalidParam(widget, name, 'spam', +- errmsg='image "spam" doesn\'t exist') +- +- def test_compound(self): +- widget = self.create() +- self.checkEnumParam(widget, 'compound', +- 'none', 'text', 'image', 'center', +- 'top', 'bottom', 'left', 'right') +- +- def test_state(self): +- widget = self.create() +- self.checkParams(widget, 'state', 'active', 'disabled', 'normal') +- +- def test_width(self): +- widget = self.create() +- self.checkParams(widget, 'width', 402, -402, 0) +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class LabelTest(AbstractLabelTest, unittest.TestCase): +- OPTIONS = ( +- 'anchor', 'background', 'borderwidth', +- 'class', 'compound', 'cursor', 'font', 'foreground', +- 'image', 'justify', 'padding', 'relief', 'state', 'style', +- 'takefocus', 'text', 'textvariable', +- 'underline', 'width', 'wraplength', +- ) +- _conv_pixels = noconv +- +- def create(self, **kwargs): +- return ttk.Label(self.root, **kwargs) +- +- def test_font(self): +- widget = self.create() +- self.checkParam(widget, 'font', +- '-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*') +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class ButtonTest(AbstractLabelTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'command', 'compound', 'cursor', 'default', +- 'image', 'padding', 'state', 'style', +- 'takefocus', 'text', 'textvariable', +- 'underline', 'width', +- ) +- +- def create(self, **kwargs): +- return ttk.Button(self.root, **kwargs) +- +- def test_default(self): +- widget = self.create() +- self.checkEnumParam(widget, 'default', 'normal', 'active', 'disabled') +- +- def test_invoke(self): +- success = [] +- btn = ttk.Button(self.root, command=lambda: success.append(1)) +- btn.invoke() +- self.assertTrue(success) +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class CheckbuttonTest(AbstractLabelTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'command', 'compound', 'cursor', +- 'image', +- 'offvalue', 'onvalue', +- 'padding', 'state', 'style', +- 'takefocus', 'text', 'textvariable', +- 'underline', 'variable', 'width', +- ) +- +- def create(self, **kwargs): +- return ttk.Checkbutton(self.root, **kwargs) +- +- def test_offvalue(self): +- widget = self.create() +- self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string') +- +- def test_onvalue(self): +- widget = self.create() +- self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string') +- +- def test_invoke(self): +- success = [] +- def cb_test(): +- success.append(1) +- return "cb test called" +- +- cbtn = ttk.Checkbutton(self.root, command=cb_test) +- # the variable automatically created by ttk.Checkbutton is actually +- # undefined till we invoke the Checkbutton +- self.assertEqual(cbtn.state(), ('alternate', )) +- self.assertRaises(tkinter.TclError, cbtn.tk.globalgetvar, +- cbtn['variable']) +- +- res = cbtn.invoke() +- self.assertEqual(res, "cb test called") +- self.assertEqual(cbtn['onvalue'], +- cbtn.tk.globalgetvar(cbtn['variable'])) +- self.assertTrue(success) +- +- cbtn['command'] = '' +- res = cbtn.invoke() +- self.assertFalse(str(res)) +- self.assertLessEqual(len(success), 1) +- self.assertEqual(cbtn['offvalue'], +- cbtn.tk.globalgetvar(cbtn['variable'])) +- +- +-@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) +-class EntryTest(AbstractWidgetTest, unittest.TestCase): +- OPTIONS = ( +- 'background', 'class', 'cursor', +- 'exportselection', 'font', 'foreground', +- 'invalidcommand', 'justify', +- 'show', 'state', 'style', 'takefocus', 'textvariable', +- 'validate', 'validatecommand', 'width', 'xscrollcommand', +- ) +- +- def setUp(self): +- super().setUp() +- self.entry = self.create() +- +- def create(self, **kwargs): +- return ttk.Entry(self.root, **kwargs) +- +- def test_invalidcommand(self): +- widget = self.create() +- self.checkCommandParam(widget, 'invalidcommand') +- +- def test_show(self): +- widget = self.create() +- self.checkParam(widget, 'show', '*') +- self.checkParam(widget, 'show', '') +- self.checkParam(widget, 'show', ' ') +- +- def test_state(self): +- widget = self.create() +- self.checkParams(widget, 'state', +- 'disabled', 'normal', 'readonly') +- +- def test_validate(self): +- widget = self.create() +- self.checkEnumParam(widget, 'validate', +- 'all', 'key', 'focus', 'focusin', 'focusout', 'none') +- +- def test_validatecommand(self): +- widget = self.create() +- self.checkCommandParam(widget, 'validatecommand') +- +- +- def test_bbox(self): +- self.assertIsBoundingBox(self.entry.bbox(0)) +- self.assertRaises(tkinter.TclError, self.entry.bbox, 'noindex') +- self.assertRaises(tkinter.TclError, self.entry.bbox, None) +- +- +- def test_identify(self): +- self.entry.pack() +- self.entry.wait_visibility() +- self.entry.update_idletasks() +- +- self.assertEqual(self.entry.identify(5, 5), "textarea") +- self.assertEqual(self.entry.identify(-1, -1), "") +- +- self.assertRaises(tkinter.TclError, self.entry.identify, None, 5) +- self.assertRaises(tkinter.TclError, self.entry.identify, 5, None) +- self.assertRaises(tkinter.TclError, self.entry.identify, 5, '') +- +- +- def test_validation_options(self): +- success = [] +- test_invalid = lambda: success.append(True) +- +- self.entry['validate'] = 'none' +- self.entry['validatecommand'] = lambda: False +- +- self.entry['invalidcommand'] = test_invalid +- self.entry.validate() +- self.assertTrue(success) +- +- self.entry['invalidcommand'] = '' +- self.entry.validate() +- self.assertEqual(len(success), 1) +- +- self.entry['invalidcommand'] = test_invalid +- self.entry['validatecommand'] = lambda: True +- self.entry.validate() +- self.assertEqual(len(success), 1) +- +- self.entry['validatecommand'] = '' +- self.entry.validate() +- self.assertEqual(len(success), 1) +- +- self.entry['validatecommand'] = True +- self.assertRaises(tkinter.TclError, self.entry.validate) +- +- +- def test_validation(self): +- validation = [] +- def validate(to_insert): +- if not 'a' <= to_insert.lower() <= 'z': +- validation.append(False) +- return False +- validation.append(True) +- return True +- +- self.entry['validate'] = 'key' +- self.entry['validatecommand'] = self.entry.register(validate), '%S' +- +- self.entry.insert('end', 1) +- self.entry.insert('end', 'a') +- self.assertEqual(validation, [False, True]) +- self.assertEqual(self.entry.get(), 'a') +- +- +- def test_revalidation(self): +- def validate(content): +- for letter in content: +- if not 'a' <= letter.lower() <= 'z': +- return False +- return True +- +- self.entry['validatecommand'] = self.entry.register(validate), '%P' +- +- self.entry.insert('end', 'avocado') +- self.assertEqual(self.entry.validate(), True) +- self.assertEqual(self.entry.state(), ()) +- +- self.entry.delete(0, 'end') +- self.assertEqual(self.entry.get(), '') +- +- self.entry.insert('end', 'a1b') +- self.assertEqual(self.entry.validate(), False) +- self.assertEqual(self.entry.state(), ('invalid', )) +- +- self.entry.delete(1) +- self.assertEqual(self.entry.validate(), True) +- self.assertEqual(self.entry.state(), ()) +- +- +-@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) +-class ComboboxTest(EntryTest, unittest.TestCase): +- OPTIONS = ( +- 'background', 'class', 'cursor', 'exportselection', +- 'font', 'foreground', 'height', 'invalidcommand', +- 'justify', 'postcommand', 'show', 'state', 'style', +- 'takefocus', 'textvariable', +- 'validate', 'validatecommand', 'values', +- 'width', 'xscrollcommand', +- ) +- +- def setUp(self): +- super().setUp() +- self.combo = self.create() +- +- def create(self, **kwargs): +- return ttk.Combobox(self.root, **kwargs) +- +- def test_height(self): +- widget = self.create() +- self.checkParams(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i') +- +- def _show_drop_down_listbox(self): +- width = self.combo.winfo_width() +- self.combo.event_generate('', x=width - 5, y=5) +- self.combo.event_generate('', x=width - 5, y=5) +- self.combo.update_idletasks() +- +- +- def test_virtual_event(self): +- success = [] +- +- self.combo['values'] = [1] +- self.combo.bind('<>', +- lambda evt: success.append(True)) +- self.combo.pack() +- self.combo.wait_visibility() +- +- height = self.combo.winfo_height() +- self._show_drop_down_listbox() +- self.combo.update() +- self.combo.event_generate('') +- self.combo.update() +- +- self.assertTrue(success) +- +- +- def test_postcommand(self): +- success = [] +- +- self.combo['postcommand'] = lambda: success.append(True) +- self.combo.pack() +- self.combo.wait_visibility() +- +- self._show_drop_down_listbox() +- self.assertTrue(success) +- +- # testing postcommand removal +- self.combo['postcommand'] = '' +- self._show_drop_down_listbox() +- self.assertEqual(len(success), 1) +- +- +- def test_values(self): +- def check_get_current(getval, currval): +- self.assertEqual(self.combo.get(), getval) +- self.assertEqual(self.combo.current(), currval) +- +- self.assertEqual(self.combo['values'], +- () if tcl_version < (8, 5) else '') +- check_get_current('', -1) +- +- self.checkParam(self.combo, 'values', 'mon tue wed thur', +- expected=('mon', 'tue', 'wed', 'thur')) +- self.checkParam(self.combo, 'values', ('mon', 'tue', 'wed', 'thur')) +- self.checkParam(self.combo, 'values', (42, 3.14, '', 'any string')) +- self.checkParam(self.combo, 'values', '', +- expected='' if get_tk_patchlevel() < (8, 5, 10) else ()) +- +- self.combo['values'] = ['a', 1, 'c'] +- +- self.combo.set('c') +- check_get_current('c', 2) +- +- self.combo.current(0) +- check_get_current('a', 0) +- +- self.combo.set('d') +- check_get_current('d', -1) +- +- # testing values with empty string +- self.combo.set('') +- self.combo['values'] = (1, 2, '', 3) +- check_get_current('', 2) +- +- # testing values with empty string set through configure +- self.combo.configure(values=[1, '', 2]) +- self.assertEqual(self.combo['values'], +- ('1', '', '2') if self.wantobjects else +- '1 {} 2') +- +- # testing values with spaces +- self.combo['values'] = ['a b', 'a\tb', 'a\nb'] +- self.assertEqual(self.combo['values'], +- ('a b', 'a\tb', 'a\nb') if self.wantobjects else +- '{a b} {a\tb} {a\nb}') +- +- # testing values with special characters +- self.combo['values'] = [r'a\tb', '"a"', '} {'] +- self.assertEqual(self.combo['values'], +- (r'a\tb', '"a"', '} {') if self.wantobjects else +- r'a\\tb {"a"} \}\ \{') +- +- # out of range +- self.assertRaises(tkinter.TclError, self.combo.current, +- len(self.combo['values'])) +- # it expects an integer (or something that can be converted to int) +- self.assertRaises(tkinter.TclError, self.combo.current, '') +- +- # testing creating combobox with empty string in values +- combo2 = ttk.Combobox(self.root, values=[1, 2, '']) +- self.assertEqual(combo2['values'], +- ('1', '2', '') if self.wantobjects else '1 2 {}') +- combo2.destroy() +- +- +-@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) +-class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'cursor', 'height', +- 'orient', 'style', 'takefocus', 'width', +- ) +- +- def setUp(self): +- super().setUp() +- self.paned = self.create() +- +- def create(self, **kwargs): +- return ttk.PanedWindow(self.root, **kwargs) +- +- def test_orient(self): +- widget = self.create() +- self.assertEqual(str(widget['orient']), 'vertical') +- errmsg='attempt to change read-only option' +- if get_tk_patchlevel() < (8, 6, 0, 'beta', 3): +- errmsg='Attempt to change read-only option' +- self.checkInvalidParam(widget, 'orient', 'horizontal', +- errmsg=errmsg) +- widget2 = self.create(orient='horizontal') +- self.assertEqual(str(widget2['orient']), 'horizontal') +- +- def test_add(self): +- # attempt to add a child that is not a direct child of the paned window +- label = ttk.Label(self.paned) +- child = ttk.Label(label) +- self.assertRaises(tkinter.TclError, self.paned.add, child) +- label.destroy() +- child.destroy() +- # another attempt +- label = ttk.Label(self.root) +- child = ttk.Label(label) +- self.assertRaises(tkinter.TclError, self.paned.add, child) +- child.destroy() +- label.destroy() +- +- good_child = ttk.Label(self.root) +- self.paned.add(good_child) +- # re-adding a child is not accepted +- self.assertRaises(tkinter.TclError, self.paned.add, good_child) +- +- other_child = ttk.Label(self.paned) +- self.paned.add(other_child) +- self.assertEqual(self.paned.pane(0), self.paned.pane(1)) +- self.assertRaises(tkinter.TclError, self.paned.pane, 2) +- good_child.destroy() +- other_child.destroy() +- self.assertRaises(tkinter.TclError, self.paned.pane, 0) +- +- +- def test_forget(self): +- self.assertRaises(tkinter.TclError, self.paned.forget, None) +- self.assertRaises(tkinter.TclError, self.paned.forget, 0) +- +- self.paned.add(ttk.Label(self.root)) +- self.paned.forget(0) +- self.assertRaises(tkinter.TclError, self.paned.forget, 0) +- +- +- def test_insert(self): +- self.assertRaises(tkinter.TclError, self.paned.insert, None, 0) +- self.assertRaises(tkinter.TclError, self.paned.insert, 0, None) +- self.assertRaises(tkinter.TclError, self.paned.insert, 0, 0) +- +- child = ttk.Label(self.root) +- child2 = ttk.Label(self.root) +- child3 = ttk.Label(self.root) +- +- self.assertRaises(tkinter.TclError, self.paned.insert, 0, child) +- +- self.paned.insert('end', child2) +- self.paned.insert(0, child) +- self.assertEqual(self.paned.panes(), (str(child), str(child2))) +- +- self.paned.insert(0, child2) +- self.assertEqual(self.paned.panes(), (str(child2), str(child))) +- +- self.paned.insert('end', child3) +- self.assertEqual(self.paned.panes(), +- (str(child2), str(child), str(child3))) +- +- # reinserting a child should move it to its current position +- panes = self.paned.panes() +- self.paned.insert('end', child3) +- self.assertEqual(panes, self.paned.panes()) +- +- # moving child3 to child2 position should result in child2 ending up +- # in previous child position and child ending up in previous child3 +- # position +- self.paned.insert(child2, child3) +- self.assertEqual(self.paned.panes(), +- (str(child3), str(child2), str(child))) +- +- +- def test_pane(self): +- self.assertRaises(tkinter.TclError, self.paned.pane, 0) +- +- child = ttk.Label(self.root) +- self.paned.add(child) +- self.assertIsInstance(self.paned.pane(0), dict) +- self.assertEqual(self.paned.pane(0, weight=None), +- 0 if self.wantobjects else '0') +- # newer form for querying a single option +- self.assertEqual(self.paned.pane(0, 'weight'), +- 0 if self.wantobjects else '0') +- self.assertEqual(self.paned.pane(0), self.paned.pane(str(child))) +- +- self.assertRaises(tkinter.TclError, self.paned.pane, 0, +- badoption='somevalue') +- +- +- def test_sashpos(self): +- self.assertRaises(tkinter.TclError, self.paned.sashpos, None) +- self.assertRaises(tkinter.TclError, self.paned.sashpos, '') +- self.assertRaises(tkinter.TclError, self.paned.sashpos, 0) +- +- child = ttk.Label(self.paned, text='a') +- self.paned.add(child, weight=1) +- self.assertRaises(tkinter.TclError, self.paned.sashpos, 0) +- child2 = ttk.Label(self.paned, text='b') +- self.paned.add(child2) +- self.assertRaises(tkinter.TclError, self.paned.sashpos, 1) +- +- self.paned.pack(expand=True, fill='both') +- self.paned.wait_visibility() +- +- curr_pos = self.paned.sashpos(0) +- self.paned.sashpos(0, 1000) +- self.assertNotEqual(curr_pos, self.paned.sashpos(0)) +- self.assertIsInstance(self.paned.sashpos(0), int) +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class RadiobuttonTest(AbstractLabelTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'command', 'compound', 'cursor', +- 'image', +- 'padding', 'state', 'style', +- 'takefocus', 'text', 'textvariable', +- 'underline', 'value', 'variable', 'width', +- ) +- +- def create(self, **kwargs): +- return ttk.Radiobutton(self.root, **kwargs) +- +- def test_value(self): +- widget = self.create() +- self.checkParams(widget, 'value', 1, 2.3, '', 'any string') +- +- def test_invoke(self): +- success = [] +- def cb_test(): +- success.append(1) +- return "cb test called" +- +- myvar = tkinter.IntVar(self.root) +- cbtn = ttk.Radiobutton(self.root, command=cb_test, +- variable=myvar, value=0) +- cbtn2 = ttk.Radiobutton(self.root, command=cb_test, +- variable=myvar, value=1) +- +- if self.wantobjects: +- conv = lambda x: x +- else: +- conv = int +- +- res = cbtn.invoke() +- self.assertEqual(res, "cb test called") +- self.assertEqual(conv(cbtn['value']), myvar.get()) +- self.assertEqual(myvar.get(), +- conv(cbtn.tk.globalgetvar(cbtn['variable']))) +- self.assertTrue(success) +- +- cbtn2['command'] = '' +- res = cbtn2.invoke() +- self.assertEqual(str(res), '') +- self.assertLessEqual(len(success), 1) +- self.assertEqual(conv(cbtn2['value']), myvar.get()) +- self.assertEqual(myvar.get(), +- conv(cbtn.tk.globalgetvar(cbtn['variable']))) +- +- self.assertEqual(str(cbtn['variable']), str(cbtn2['variable'])) +- +- +-class MenubuttonTest(AbstractLabelTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'compound', 'cursor', 'direction', +- 'image', 'menu', 'padding', 'state', 'style', +- 'takefocus', 'text', 'textvariable', +- 'underline', 'width', +- ) +- +- def create(self, **kwargs): +- return ttk.Menubutton(self.root, **kwargs) +- +- def test_direction(self): +- widget = self.create() +- self.checkEnumParam(widget, 'direction', +- 'above', 'below', 'left', 'right', 'flush') +- +- def test_menu(self): +- widget = self.create() +- menu = tkinter.Menu(widget, name='menu') +- self.checkParam(widget, 'menu', menu, conv=str) +- menu.destroy() +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class ScaleTest(AbstractWidgetTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'command', 'cursor', 'from', 'length', +- 'orient', 'style', 'takefocus', 'to', 'value', 'variable', +- ) +- _conv_pixels = noconv +- default_orient = 'horizontal' +- +- def setUp(self): +- super().setUp() +- self.scale = self.create() +- self.scale.pack() +- self.scale.update() +- +- def create(self, **kwargs): +- return ttk.Scale(self.root, **kwargs) +- +- def test_from(self): +- widget = self.create() +- self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=False) +- +- def test_length(self): +- widget = self.create() +- self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i') +- +- def test_to(self): +- widget = self.create() +- self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10, conv=False) +- +- def test_value(self): +- widget = self.create() +- self.checkFloatParam(widget, 'value', 300, 14.9, 15.1, -10, conv=False) +- +- def test_custom_event(self): +- failure = [1, 1, 1] # will need to be empty +- +- funcid = self.scale.bind('<>', lambda evt: failure.pop()) +- +- self.scale['from'] = 10 +- self.scale['from_'] = 10 +- self.scale['to'] = 3 +- +- self.assertFalse(failure) +- +- failure = [1, 1, 1] +- self.scale.configure(from_=2, to=5) +- self.scale.configure(from_=0, to=-2) +- self.scale.configure(to=10) +- +- self.assertFalse(failure) +- +- +- def test_get(self): +- if self.wantobjects: +- conv = lambda x: x +- else: +- conv = float +- +- scale_width = self.scale.winfo_width() +- self.assertEqual(self.scale.get(scale_width, 0), self.scale['to']) +- +- self.assertEqual(conv(self.scale.get(0, 0)), conv(self.scale['from'])) +- self.assertEqual(self.scale.get(), self.scale['value']) +- self.scale['value'] = 30 +- self.assertEqual(self.scale.get(), self.scale['value']) +- +- self.assertRaises(tkinter.TclError, self.scale.get, '', 0) +- self.assertRaises(tkinter.TclError, self.scale.get, 0, '') +- +- +- def test_set(self): +- if self.wantobjects: +- conv = lambda x: x +- else: +- conv = float +- +- # set restricts the max/min values according to the current range +- max = conv(self.scale['to']) +- new_max = max + 10 +- self.scale.set(new_max) +- self.assertEqual(conv(self.scale.get()), max) +- min = conv(self.scale['from']) +- self.scale.set(min - 1) +- self.assertEqual(conv(self.scale.get()), min) +- +- # changing directly the variable doesn't impose this limitation tho +- var = tkinter.DoubleVar(self.root) +- self.scale['variable'] = var +- var.set(max + 5) +- self.assertEqual(conv(self.scale.get()), var.get()) +- self.assertEqual(conv(self.scale.get()), max + 5) +- del var +- +- # the same happens with the value option +- self.scale['value'] = max + 10 +- self.assertEqual(conv(self.scale.get()), max + 10) +- self.assertEqual(conv(self.scale.get()), conv(self.scale['value'])) +- +- # nevertheless, note that the max/min values we can get specifying +- # x, y coords are the ones according to the current range +- self.assertEqual(conv(self.scale.get(0, 0)), min) +- self.assertEqual(conv(self.scale.get(self.scale.winfo_width(), 0)), max) +- +- self.assertRaises(tkinter.TclError, self.scale.set, None) +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class ProgressbarTest(AbstractWidgetTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'cursor', 'orient', 'length', +- 'mode', 'maximum', 'phase', +- 'style', 'takefocus', 'value', 'variable', +- ) +- _conv_pixels = noconv +- default_orient = 'horizontal' +- +- def create(self, **kwargs): +- return ttk.Progressbar(self.root, **kwargs) +- +- def test_length(self): +- widget = self.create() +- self.checkPixelsParam(widget, 'length', 100.1, 56.7, '2i') +- +- def test_maximum(self): +- widget = self.create() +- self.checkFloatParam(widget, 'maximum', 150.2, 77.7, 0, -10, conv=False) +- +- def test_mode(self): +- widget = self.create() +- self.checkEnumParam(widget, 'mode', 'determinate', 'indeterminate') +- +- def test_phase(self): +- # XXX +- pass +- +- def test_value(self): +- widget = self.create() +- self.checkFloatParam(widget, 'value', 150.2, 77.7, 0, -10, +- conv=False) +- +- +-@unittest.skipIf(sys.platform == 'darwin', +- 'ttk.Scrollbar is special on MacOSX') +-@add_standard_options(StandardTtkOptionsTests) +-class ScrollbarTest(AbstractWidgetTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'command', 'cursor', 'orient', 'style', 'takefocus', +- ) +- default_orient = 'vertical' +- +- def create(self, **kwargs): +- return ttk.Scrollbar(self.root, **kwargs) +- +- +-@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) +-class NotebookTest(AbstractWidgetTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'cursor', 'height', 'padding', 'style', 'takefocus', 'width', +- ) +- +- def setUp(self): +- super().setUp() +- self.nb = self.create(padding=0) +- self.child1 = ttk.Label(self.root) +- self.child2 = ttk.Label(self.root) +- self.nb.add(self.child1, text='a') +- self.nb.add(self.child2, text='b') +- +- def create(self, **kwargs): +- return ttk.Notebook(self.root, **kwargs) +- +- def test_tab_identifiers(self): +- self.nb.forget(0) +- self.nb.hide(self.child2) +- self.assertRaises(tkinter.TclError, self.nb.tab, self.child1) +- self.assertEqual(self.nb.index('end'), 1) +- self.nb.add(self.child2) +- self.assertEqual(self.nb.index('end'), 1) +- self.nb.select(self.child2) +- +- self.assertTrue(self.nb.tab('current')) +- self.nb.add(self.child1, text='a') +- +- self.nb.pack() +- self.nb.wait_visibility() +- if sys.platform == 'darwin': +- tb_idx = "@20,5" +- else: +- tb_idx = "@5,5" +- self.assertEqual(self.nb.tab(tb_idx), self.nb.tab('current')) +- +- for i in range(5, 100, 5): +- try: +- if self.nb.tab('@%d, 5' % i, text=None) == 'a': +- break +- except tkinter.TclError: +- pass +- +- else: +- self.fail("Tab with text 'a' not found") +- +- +- def test_add_and_hidden(self): +- self.assertRaises(tkinter.TclError, self.nb.hide, -1) +- self.assertRaises(tkinter.TclError, self.nb.hide, 'hi') +- self.assertRaises(tkinter.TclError, self.nb.hide, None) +- self.assertRaises(tkinter.TclError, self.nb.add, None) +- self.assertRaises(tkinter.TclError, self.nb.add, ttk.Label(self.root), +- unknown='option') +- +- tabs = self.nb.tabs() +- self.nb.hide(self.child1) +- self.nb.add(self.child1) +- self.assertEqual(self.nb.tabs(), tabs) +- +- child = ttk.Label(self.root) +- self.nb.add(child, text='c') +- tabs = self.nb.tabs() +- +- curr = self.nb.index('current') +- # verify that the tab gets readded at its previous position +- child2_index = self.nb.index(self.child2) +- self.nb.hide(self.child2) +- self.nb.add(self.child2) +- self.assertEqual(self.nb.tabs(), tabs) +- self.assertEqual(self.nb.index(self.child2), child2_index) +- self.assertEqual(str(self.child2), self.nb.tabs()[child2_index]) +- # but the tab next to it (not hidden) is the one selected now +- self.assertEqual(self.nb.index('current'), curr + 1) +- +- +- def test_forget(self): +- self.assertRaises(tkinter.TclError, self.nb.forget, -1) +- self.assertRaises(tkinter.TclError, self.nb.forget, 'hi') +- self.assertRaises(tkinter.TclError, self.nb.forget, None) +- +- tabs = self.nb.tabs() +- child1_index = self.nb.index(self.child1) +- self.nb.forget(self.child1) +- self.assertNotIn(str(self.child1), self.nb.tabs()) +- self.assertEqual(len(tabs) - 1, len(self.nb.tabs())) +- +- self.nb.add(self.child1) +- self.assertEqual(self.nb.index(self.child1), 1) +- self.assertNotEqual(child1_index, self.nb.index(self.child1)) +- +- +- def test_index(self): +- self.assertRaises(tkinter.TclError, self.nb.index, -1) +- self.assertRaises(tkinter.TclError, self.nb.index, None) +- +- self.assertIsInstance(self.nb.index('end'), int) +- self.assertEqual(self.nb.index(self.child1), 0) +- self.assertEqual(self.nb.index(self.child2), 1) +- self.assertEqual(self.nb.index('end'), 2) +- +- +- def test_insert(self): +- # moving tabs +- tabs = self.nb.tabs() +- self.nb.insert(1, tabs[0]) +- self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0])) +- self.nb.insert(self.child1, self.child2) +- self.assertEqual(self.nb.tabs(), tabs) +- self.nb.insert('end', self.child1) +- self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0])) +- self.nb.insert('end', 0) +- self.assertEqual(self.nb.tabs(), tabs) +- # bad moves +- self.assertRaises(tkinter.TclError, self.nb.insert, 2, tabs[0]) +- self.assertRaises(tkinter.TclError, self.nb.insert, -1, tabs[0]) +- +- # new tab +- child3 = ttk.Label(self.root) +- self.nb.insert(1, child3) +- self.assertEqual(self.nb.tabs(), (tabs[0], str(child3), tabs[1])) +- self.nb.forget(child3) +- self.assertEqual(self.nb.tabs(), tabs) +- self.nb.insert(self.child1, child3) +- self.assertEqual(self.nb.tabs(), (str(child3), ) + tabs) +- self.nb.forget(child3) +- self.assertRaises(tkinter.TclError, self.nb.insert, 2, child3) +- self.assertRaises(tkinter.TclError, self.nb.insert, -1, child3) +- +- # bad inserts +- self.assertRaises(tkinter.TclError, self.nb.insert, 'end', None) +- self.assertRaises(tkinter.TclError, self.nb.insert, None, 0) +- self.assertRaises(tkinter.TclError, self.nb.insert, None, None) +- +- +- def test_select(self): +- self.nb.pack() +- self.nb.wait_visibility() +- +- success = [] +- tab_changed = [] +- +- self.child1.bind('', lambda evt: success.append(True)) +- self.nb.bind('<>', +- lambda evt: tab_changed.append(True)) +- +- self.assertEqual(self.nb.select(), str(self.child1)) +- self.nb.select(self.child2) +- self.assertTrue(success) +- self.assertEqual(self.nb.select(), str(self.child2)) +- +- self.nb.update() +- self.assertTrue(tab_changed) +- +- +- def test_tab(self): +- self.assertRaises(tkinter.TclError, self.nb.tab, -1) +- self.assertRaises(tkinter.TclError, self.nb.tab, 'notab') +- self.assertRaises(tkinter.TclError, self.nb.tab, None) +- +- self.assertIsInstance(self.nb.tab(self.child1), dict) +- self.assertEqual(self.nb.tab(self.child1, text=None), 'a') +- # newer form for querying a single option +- self.assertEqual(self.nb.tab(self.child1, 'text'), 'a') +- self.nb.tab(self.child1, text='abc') +- self.assertEqual(self.nb.tab(self.child1, text=None), 'abc') +- self.assertEqual(self.nb.tab(self.child1, 'text'), 'abc') +- +- +- def test_tabs(self): +- self.assertEqual(len(self.nb.tabs()), 2) +- +- self.nb.forget(self.child1) +- self.nb.forget(self.child2) +- +- self.assertEqual(self.nb.tabs(), ()) +- +- +- def test_traversal(self): +- self.nb.pack() +- self.nb.wait_visibility() +- +- self.nb.select(0) +- +- simulate_mouse_click(self.nb, 5, 5) +- self.nb.focus_force() +- self.nb.event_generate('') +- self.assertEqual(self.nb.select(), str(self.child2)) +- self.nb.focus_force() +- self.nb.event_generate('') +- self.assertEqual(self.nb.select(), str(self.child1)) +- self.nb.focus_force() +- self.nb.event_generate('') +- self.assertEqual(self.nb.select(), str(self.child2)) +- +- self.nb.tab(self.child1, text='a', underline=0) +- self.nb.enable_traversal() +- self.nb.focus_force() +- simulate_mouse_click(self.nb, 5, 5) +- if sys.platform == 'darwin': +- self.nb.event_generate('') +- else: +- self.nb.event_generate('') +- self.assertEqual(self.nb.select(), str(self.child1)) +- +-@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) +-class SpinboxTest(EntryTest, unittest.TestCase): +- OPTIONS = ( +- 'background', 'class', 'command', 'cursor', 'exportselection', +- 'font', 'foreground', 'format', 'from', 'increment', +- 'invalidcommand', 'justify', 'show', 'state', 'style', +- 'takefocus', 'textvariable', 'to', 'validate', 'validatecommand', +- 'values', 'width', 'wrap', 'xscrollcommand', +- ) +- +- def setUp(self): +- super().setUp() +- self.spin = self.create() +- self.spin.pack() +- +- def create(self, **kwargs): +- return ttk.Spinbox(self.root, **kwargs) +- +- def _click_increment_arrow(self): +- width = self.spin.winfo_width() +- height = self.spin.winfo_height() +- x = width - 5 +- y = height//2 - 5 +- self.spin.event_generate('', x=x, y=y) +- self.spin.event_generate('', x=x, y=y) +- self.spin.update_idletasks() +- +- def _click_decrement_arrow(self): +- width = self.spin.winfo_width() +- height = self.spin.winfo_height() +- x = width - 5 +- y = height//2 + 4 +- self.spin.event_generate('', x=x, y=y) +- self.spin.event_generate('', x=x, y=y) +- self.spin.update_idletasks() +- +- def test_command(self): +- success = [] +- +- self.spin['command'] = lambda: success.append(True) +- self.spin.update() +- self._click_increment_arrow() +- self.spin.update() +- self.assertTrue(success) +- +- self._click_decrement_arrow() +- self.assertEqual(len(success), 2) +- +- # testing postcommand removal +- self.spin['command'] = '' +- self.spin.update_idletasks() +- self._click_increment_arrow() +- self._click_decrement_arrow() +- self.spin.update() +- self.assertEqual(len(success), 2) +- +- def test_to(self): +- self.spin['from'] = 0 +- self.spin['to'] = 5 +- self.spin.set(4) +- self.spin.update() +- self._click_increment_arrow() # 5 +- +- self.assertEqual(self.spin.get(), '5') +- +- self._click_increment_arrow() # 5 +- self.assertEqual(self.spin.get(), '5') +- +- def test_from(self): +- self.spin['from'] = 1 +- self.spin['to'] = 10 +- self.spin.set(2) +- self.spin.update() +- self._click_decrement_arrow() # 1 +- self.assertEqual(self.spin.get(), '1') +- self._click_decrement_arrow() # 1 +- self.assertEqual(self.spin.get(), '1') +- +- def test_increment(self): +- self.spin['from'] = 0 +- self.spin['to'] = 10 +- self.spin['increment'] = 4 +- self.spin.set(1) +- self.spin.update() +- +- self._click_increment_arrow() # 5 +- self.assertEqual(self.spin.get(), '5') +- self.spin['increment'] = 2 +- self.spin.update() +- self._click_decrement_arrow() # 3 +- self.assertEqual(self.spin.get(), '3') +- +- def test_format(self): +- self.spin.set(1) +- self.spin['format'] = '%10.3f' +- self.spin.update() +- self._click_increment_arrow() +- value = self.spin.get() +- +- self.assertEqual(len(value), 10) +- self.assertEqual(value.index('.'), 6) +- +- self.spin['format'] = '' +- self.spin.update() +- self._click_increment_arrow() +- value = self.spin.get() +- self.assertTrue('.' not in value) +- self.assertEqual(len(value), 1) +- +- def test_wrap(self): +- self.spin['to'] = 10 +- self.spin['from'] = 1 +- self.spin.set(1) +- self.spin['wrap'] = True +- self.spin.update() +- +- self._click_decrement_arrow() +- self.assertEqual(self.spin.get(), '10') +- +- self._click_increment_arrow() +- self.assertEqual(self.spin.get(), '1') +- +- self.spin['wrap'] = False +- self.spin.update() +- +- self._click_decrement_arrow() +- self.assertEqual(self.spin.get(), '1') +- +- def test_values(self): +- self.assertEqual(self.spin['values'], +- () if tcl_version < (8, 5) else '') +- self.checkParam(self.spin, 'values', 'mon tue wed thur', +- expected=('mon', 'tue', 'wed', 'thur')) +- self.checkParam(self.spin, 'values', ('mon', 'tue', 'wed', 'thur')) +- self.checkParam(self.spin, 'values', (42, 3.14, '', 'any string')) +- self.checkParam( +- self.spin, +- 'values', +- '', +- expected='' if get_tk_patchlevel() < (8, 5, 10) else () +- ) +- +- self.spin['values'] = ['a', 1, 'c'] +- +- # test incrementing / decrementing values +- self.spin.set('a') +- self.spin.update() +- self._click_increment_arrow() +- self.assertEqual(self.spin.get(), '1') +- +- self._click_decrement_arrow() +- self.assertEqual(self.spin.get(), 'a') +- +- # testing values with empty string set through configure +- self.spin.configure(values=[1, '', 2]) +- self.assertEqual(self.spin['values'], +- ('1', '', '2') if self.wantobjects else +- '1 {} 2') +- +- # testing values with spaces +- self.spin['values'] = ['a b', 'a\tb', 'a\nb'] +- self.assertEqual(self.spin['values'], +- ('a b', 'a\tb', 'a\nb') if self.wantobjects else +- '{a b} {a\tb} {a\nb}') +- +- # testing values with special characters +- self.spin['values'] = [r'a\tb', '"a"', '} {'] +- self.assertEqual(self.spin['values'], +- (r'a\tb', '"a"', '} {') if self.wantobjects else +- r'a\\tb {"a"} \}\ \{') +- +- # testing creating spinbox with empty string in values +- spin2 = ttk.Spinbox(self.root, values=[1, 2, '']) +- self.assertEqual(spin2['values'], +- ('1', '2', '') if self.wantobjects else '1 2 {}') +- spin2.destroy() +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class TreeviewTest(AbstractWidgetTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'columns', 'cursor', 'displaycolumns', +- 'height', 'padding', 'selectmode', 'show', +- 'style', 'takefocus', 'xscrollcommand', 'yscrollcommand', +- ) +- +- def setUp(self): +- super().setUp() +- self.tv = self.create(padding=0) +- +- def create(self, **kwargs): +- return ttk.Treeview(self.root, **kwargs) +- +- def test_columns(self): +- widget = self.create() +- self.checkParam(widget, 'columns', 'a b c', +- expected=('a', 'b', 'c')) +- self.checkParam(widget, 'columns', ('a', 'b', 'c')) +- self.checkParam(widget, 'columns', (), +- expected='' if get_tk_patchlevel() < (8, 5, 10) else ()) +- +- def test_displaycolumns(self): +- widget = self.create() +- widget['columns'] = ('a', 'b', 'c') +- self.checkParam(widget, 'displaycolumns', 'b a c', +- expected=('b', 'a', 'c')) +- self.checkParam(widget, 'displaycolumns', ('b', 'a', 'c')) +- self.checkParam(widget, 'displaycolumns', '#all', +- expected=('#all',)) +- self.checkParam(widget, 'displaycolumns', (2, 1, 0)) +- self.checkInvalidParam(widget, 'displaycolumns', ('a', 'b', 'd'), +- errmsg='Invalid column index d') +- self.checkInvalidParam(widget, 'displaycolumns', (1, 2, 3), +- errmsg='Column index 3 out of bounds') +- self.checkInvalidParam(widget, 'displaycolumns', (1, -2), +- errmsg='Column index -2 out of bounds') +- +- def test_height(self): +- widget = self.create() +- self.checkPixelsParam(widget, 'height', 100, -100, 0, '3c', conv=False) +- self.checkPixelsParam(widget, 'height', 101.2, 102.6, conv=noconv) +- +- def test_selectmode(self): +- widget = self.create() +- self.checkEnumParam(widget, 'selectmode', +- 'none', 'browse', 'extended') +- +- def test_show(self): +- widget = self.create() +- self.checkParam(widget, 'show', 'tree headings', +- expected=('tree', 'headings')) +- self.checkParam(widget, 'show', ('tree', 'headings')) +- self.checkParam(widget, 'show', ('headings', 'tree')) +- self.checkParam(widget, 'show', 'tree', expected=('tree',)) +- self.checkParam(widget, 'show', 'headings', expected=('headings',)) +- +- def test_bbox(self): +- self.tv.pack() +- self.assertEqual(self.tv.bbox(''), '') +- self.tv.wait_visibility() +- self.tv.update() +- +- item_id = self.tv.insert('', 'end') +- children = self.tv.get_children() +- self.assertTrue(children) +- +- bbox = self.tv.bbox(children[0]) +- self.assertIsBoundingBox(bbox) +- +- # compare width in bboxes +- self.tv['columns'] = ['test'] +- self.tv.column('test', width=50) +- bbox_column0 = self.tv.bbox(children[0], 0) +- root_width = self.tv.column('#0', width=None) +- if not self.wantobjects: +- root_width = int(root_width) +- self.assertEqual(bbox_column0[0], bbox[0] + root_width) +- +- # verify that bbox of a closed item is the empty string +- child1 = self.tv.insert(item_id, 'end') +- self.assertEqual(self.tv.bbox(child1), '') +- +- +- def test_children(self): +- # no children yet, should get an empty tuple +- self.assertEqual(self.tv.get_children(), ()) +- +- item_id = self.tv.insert('', 'end') +- self.assertIsInstance(self.tv.get_children(), tuple) +- self.assertEqual(self.tv.get_children()[0], item_id) +- +- # add item_id and child3 as children of child2 +- child2 = self.tv.insert('', 'end') +- child3 = self.tv.insert('', 'end') +- self.tv.set_children(child2, item_id, child3) +- self.assertEqual(self.tv.get_children(child2), (item_id, child3)) +- +- # child3 has child2 as parent, thus trying to set child2 as a children +- # of child3 should result in an error +- self.assertRaises(tkinter.TclError, +- self.tv.set_children, child3, child2) +- +- # remove child2 children +- self.tv.set_children(child2) +- self.assertEqual(self.tv.get_children(child2), ()) +- +- # remove root's children +- self.tv.set_children('') +- self.assertEqual(self.tv.get_children(), ()) +- +- +- def test_column(self): +- # return a dict with all options/values +- self.assertIsInstance(self.tv.column('#0'), dict) +- # return a single value of the given option +- if self.wantobjects: +- self.assertIsInstance(self.tv.column('#0', width=None), int) +- # set a new value for an option +- self.tv.column('#0', width=10) +- # testing new way to get option value +- self.assertEqual(self.tv.column('#0', 'width'), +- 10 if self.wantobjects else '10') +- self.assertEqual(self.tv.column('#0', width=None), +- 10 if self.wantobjects else '10') +- # check read-only option +- self.assertRaises(tkinter.TclError, self.tv.column, '#0', id='X') +- +- self.assertRaises(tkinter.TclError, self.tv.column, 'invalid') +- invalid_kws = [ +- {'unknown_option': 'some value'}, {'stretch': 'wrong'}, +- {'anchor': 'wrong'}, {'width': 'wrong'}, {'minwidth': 'wrong'} +- ] +- for kw in invalid_kws: +- self.assertRaises(tkinter.TclError, self.tv.column, '#0', +- **kw) +- +- +- def test_delete(self): +- self.assertRaises(tkinter.TclError, self.tv.delete, '#0') +- +- item_id = self.tv.insert('', 'end') +- item2 = self.tv.insert(item_id, 'end') +- self.assertEqual(self.tv.get_children(), (item_id, )) +- self.assertEqual(self.tv.get_children(item_id), (item2, )) +- +- self.tv.delete(item_id) +- self.assertFalse(self.tv.get_children()) +- +- # reattach should fail +- self.assertRaises(tkinter.TclError, +- self.tv.reattach, item_id, '', 'end') +- +- # test multiple item delete +- item1 = self.tv.insert('', 'end') +- item2 = self.tv.insert('', 'end') +- self.assertEqual(self.tv.get_children(), (item1, item2)) +- +- self.tv.delete(item1, item2) +- self.assertFalse(self.tv.get_children()) +- +- +- def test_detach_reattach(self): +- item_id = self.tv.insert('', 'end') +- item2 = self.tv.insert(item_id, 'end') +- +- # calling detach without items is valid, although it does nothing +- prev = self.tv.get_children() +- self.tv.detach() # this should do nothing +- self.assertEqual(prev, self.tv.get_children()) +- +- self.assertEqual(self.tv.get_children(), (item_id, )) +- self.assertEqual(self.tv.get_children(item_id), (item2, )) +- +- # detach item with children +- self.tv.detach(item_id) +- self.assertFalse(self.tv.get_children()) +- +- # reattach item with children +- self.tv.reattach(item_id, '', 'end') +- self.assertEqual(self.tv.get_children(), (item_id, )) +- self.assertEqual(self.tv.get_children(item_id), (item2, )) +- +- # move a children to the root +- self.tv.move(item2, '', 'end') +- self.assertEqual(self.tv.get_children(), (item_id, item2)) +- self.assertEqual(self.tv.get_children(item_id), ()) +- +- # bad values +- self.assertRaises(tkinter.TclError, +- self.tv.reattach, 'nonexistent', '', 'end') +- self.assertRaises(tkinter.TclError, +- self.tv.detach, 'nonexistent') +- self.assertRaises(tkinter.TclError, +- self.tv.reattach, item2, 'otherparent', 'end') +- self.assertRaises(tkinter.TclError, +- self.tv.reattach, item2, '', 'invalid') +- +- # multiple detach +- self.tv.detach(item_id, item2) +- self.assertEqual(self.tv.get_children(), ()) +- self.assertEqual(self.tv.get_children(item_id), ()) +- +- +- def test_exists(self): +- self.assertEqual(self.tv.exists('something'), False) +- self.assertEqual(self.tv.exists(''), True) +- self.assertEqual(self.tv.exists({}), False) +- +- # the following will make a tk.call equivalent to +- # tk.call(treeview, "exists") which should result in an error +- # in the tcl interpreter since tk requires an item. +- self.assertRaises(tkinter.TclError, self.tv.exists, None) +- +- +- def test_focus(self): +- # nothing is focused right now +- self.assertEqual(self.tv.focus(), '') +- +- item1 = self.tv.insert('', 'end') +- self.tv.focus(item1) +- self.assertEqual(self.tv.focus(), item1) +- +- self.tv.delete(item1) +- self.assertEqual(self.tv.focus(), '') +- +- # try focusing inexistent item +- self.assertRaises(tkinter.TclError, self.tv.focus, 'hi') +- +- +- def test_heading(self): +- # check a dict is returned +- self.assertIsInstance(self.tv.heading('#0'), dict) +- +- # check a value is returned +- self.tv.heading('#0', text='hi') +- self.assertEqual(self.tv.heading('#0', 'text'), 'hi') +- self.assertEqual(self.tv.heading('#0', text=None), 'hi') +- +- # invalid option +- self.assertRaises(tkinter.TclError, self.tv.heading, '#0', +- background=None) +- # invalid value +- self.assertRaises(tkinter.TclError, self.tv.heading, '#0', +- anchor=1) +- +- def test_heading_callback(self): +- def simulate_heading_click(x, y): +- simulate_mouse_click(self.tv, x, y) +- self.tv.update() +- +- success = [] # no success for now +- +- self.tv.pack() +- self.tv.wait_visibility() +- self.tv.heading('#0', command=lambda: success.append(True)) +- self.tv.column('#0', width=100) +- self.tv.update() +- +- # assuming that the coords (5, 5) fall into heading #0 +- simulate_heading_click(5, 5) +- if not success: +- self.fail("The command associated to the treeview heading wasn't " +- "invoked.") +- +- success = [] +- commands = self.tv.master._tclCommands +- self.tv.heading('#0', command=str(self.tv.heading('#0', command=None))) +- self.assertEqual(commands, self.tv.master._tclCommands) +- simulate_heading_click(5, 5) +- if not success: +- self.fail("The command associated to the treeview heading wasn't " +- "invoked.") +- +- # XXX The following raises an error in a tcl interpreter, but not in +- # Python +- #self.tv.heading('#0', command='I dont exist') +- #simulate_heading_click(5, 5) +- +- +- def test_index(self): +- # item 'what' doesn't exist +- self.assertRaises(tkinter.TclError, self.tv.index, 'what') +- +- self.assertEqual(self.tv.index(''), 0) +- +- item1 = self.tv.insert('', 'end') +- item2 = self.tv.insert('', 'end') +- c1 = self.tv.insert(item1, 'end') +- c2 = self.tv.insert(item1, 'end') +- self.assertEqual(self.tv.index(item1), 0) +- self.assertEqual(self.tv.index(c1), 0) +- self.assertEqual(self.tv.index(c2), 1) +- self.assertEqual(self.tv.index(item2), 1) +- +- self.tv.move(item2, '', 0) +- self.assertEqual(self.tv.index(item2), 0) +- self.assertEqual(self.tv.index(item1), 1) +- +- # check that index still works even after its parent and siblings +- # have been detached +- self.tv.detach(item1) +- self.assertEqual(self.tv.index(c2), 1) +- self.tv.detach(c1) +- self.assertEqual(self.tv.index(c2), 0) +- +- # but it fails after item has been deleted +- self.tv.delete(item1) +- self.assertRaises(tkinter.TclError, self.tv.index, c2) +- +- +- def test_insert_item(self): +- # parent 'none' doesn't exist +- self.assertRaises(tkinter.TclError, self.tv.insert, 'none', 'end') +- +- # open values +- self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', +- open='') +- self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', +- open='please') +- self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=True))) +- self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=False))) +- +- # invalid index +- self.assertRaises(tkinter.TclError, self.tv.insert, '', 'middle') +- +- # trying to duplicate item id is invalid +- itemid = self.tv.insert('', 'end', 'first-item') +- self.assertEqual(itemid, 'first-item') +- self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', +- 'first-item') +- self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', +- MockTclObj('first-item')) +- +- # unicode values +- value = '\xe1ba' +- item = self.tv.insert('', 'end', values=(value, )) +- self.assertEqual(self.tv.item(item, 'values'), +- (value,) if self.wantobjects else value) +- self.assertEqual(self.tv.item(item, values=None), +- (value,) if self.wantobjects else value) +- +- self.tv.item(item, values=self.root.splitlist(self.tv.item(item, values=None))) +- self.assertEqual(self.tv.item(item, values=None), +- (value,) if self.wantobjects else value) +- +- self.assertIsInstance(self.tv.item(item), dict) +- +- # erase item values +- self.tv.item(item, values='') +- self.assertFalse(self.tv.item(item, values=None)) +- +- # item tags +- item = self.tv.insert('', 'end', tags=[1, 2, value]) +- self.assertEqual(self.tv.item(item, tags=None), +- ('1', '2', value) if self.wantobjects else +- '1 2 %s' % value) +- self.tv.item(item, tags=[]) +- self.assertFalse(self.tv.item(item, tags=None)) +- self.tv.item(item, tags=(1, 2)) +- self.assertEqual(self.tv.item(item, tags=None), +- ('1', '2') if self.wantobjects else '1 2') +- +- # values with spaces +- item = self.tv.insert('', 'end', values=('a b c', +- '%s %s' % (value, value))) +- self.assertEqual(self.tv.item(item, values=None), +- ('a b c', '%s %s' % (value, value)) if self.wantobjects else +- '{a b c} {%s %s}' % (value, value)) +- +- # text +- self.assertEqual(self.tv.item( +- self.tv.insert('', 'end', text="Label here"), text=None), +- "Label here") +- self.assertEqual(self.tv.item( +- self.tv.insert('', 'end', text=value), text=None), +- value) +- +- # test for values which are not None +- itemid = self.tv.insert('', 'end', 0) +- self.assertEqual(itemid, '0') +- itemid = self.tv.insert('', 'end', 0.0) +- self.assertEqual(itemid, '0.0') +- # this is because False resolves to 0 and element with 0 iid is already present +- self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', False) +- self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', '') +- +- +- def test_selection(self): +- self.assertRaises(TypeError, self.tv.selection, 'spam') +- # item 'none' doesn't exist +- self.assertRaises(tkinter.TclError, self.tv.selection_set, 'none') +- self.assertRaises(tkinter.TclError, self.tv.selection_add, 'none') +- self.assertRaises(tkinter.TclError, self.tv.selection_remove, 'none') +- self.assertRaises(tkinter.TclError, self.tv.selection_toggle, 'none') +- +- item1 = self.tv.insert('', 'end') +- item2 = self.tv.insert('', 'end') +- c1 = self.tv.insert(item1, 'end') +- c2 = self.tv.insert(item1, 'end') +- c3 = self.tv.insert(item1, 'end') +- self.assertEqual(self.tv.selection(), ()) +- +- self.tv.selection_set(c1, item2) +- self.assertEqual(self.tv.selection(), (c1, item2)) +- self.tv.selection_set(c2) +- self.assertEqual(self.tv.selection(), (c2,)) +- +- self.tv.selection_add(c1, item2) +- self.assertEqual(self.tv.selection(), (c1, c2, item2)) +- self.tv.selection_add(item1) +- self.assertEqual(self.tv.selection(), (item1, c1, c2, item2)) +- self.tv.selection_add() +- self.assertEqual(self.tv.selection(), (item1, c1, c2, item2)) +- +- self.tv.selection_remove(item1, c3) +- self.assertEqual(self.tv.selection(), (c1, c2, item2)) +- self.tv.selection_remove(c2) +- self.assertEqual(self.tv.selection(), (c1, item2)) +- self.tv.selection_remove() +- self.assertEqual(self.tv.selection(), (c1, item2)) +- +- self.tv.selection_toggle(c1, c3) +- self.assertEqual(self.tv.selection(), (c3, item2)) +- self.tv.selection_toggle(item2) +- self.assertEqual(self.tv.selection(), (c3,)) +- self.tv.selection_toggle() +- self.assertEqual(self.tv.selection(), (c3,)) +- +- self.tv.insert('', 'end', id='with spaces') +- self.tv.selection_set('with spaces') +- self.assertEqual(self.tv.selection(), ('with spaces',)) +- +- self.tv.insert('', 'end', id='{brace') +- self.tv.selection_set('{brace') +- self.assertEqual(self.tv.selection(), ('{brace',)) +- +- self.tv.insert('', 'end', id='unicode\u20ac') +- self.tv.selection_set('unicode\u20ac') +- self.assertEqual(self.tv.selection(), ('unicode\u20ac',)) +- +- self.tv.insert('', 'end', id=b'bytes\xe2\x82\xac') +- self.tv.selection_set(b'bytes\xe2\x82\xac') +- self.assertEqual(self.tv.selection(), ('bytes\xe2\x82\xac',)) +- +- self.tv.selection_set() +- self.assertEqual(self.tv.selection(), ()) +- +- # Old interface +- self.tv.selection_set((c1, item2)) +- self.assertEqual(self.tv.selection(), (c1, item2)) +- self.tv.selection_add((c1, item1)) +- self.assertEqual(self.tv.selection(), (item1, c1, item2)) +- self.tv.selection_remove((item1, c3)) +- self.assertEqual(self.tv.selection(), (c1, item2)) +- self.tv.selection_toggle((c1, c3)) +- self.assertEqual(self.tv.selection(), (c3, item2)) +- +- +- def test_set(self): +- self.tv['columns'] = ['A', 'B'] +- item = self.tv.insert('', 'end', values=['a', 'b']) +- self.assertEqual(self.tv.set(item), {'A': 'a', 'B': 'b'}) +- +- self.tv.set(item, 'B', 'a') +- self.assertEqual(self.tv.item(item, values=None), +- ('a', 'a') if self.wantobjects else 'a a') +- +- self.tv['columns'] = ['B'] +- self.assertEqual(self.tv.set(item), {'B': 'a'}) +- +- self.tv.set(item, 'B', 'b') +- self.assertEqual(self.tv.set(item, column='B'), 'b') +- self.assertEqual(self.tv.item(item, values=None), +- ('b', 'a') if self.wantobjects else 'b a') +- +- self.tv.set(item, 'B', 123) +- self.assertEqual(self.tv.set(item, 'B'), +- 123 if self.wantobjects else '123') +- self.assertEqual(self.tv.item(item, values=None), +- (123, 'a') if self.wantobjects else '123 a') +- self.assertEqual(self.tv.set(item), +- {'B': 123} if self.wantobjects else {'B': '123'}) +- +- # inexistent column +- self.assertRaises(tkinter.TclError, self.tv.set, item, 'A') +- self.assertRaises(tkinter.TclError, self.tv.set, item, 'A', 'b') +- +- # inexistent item +- self.assertRaises(tkinter.TclError, self.tv.set, 'notme') +- +- +- def test_tag_bind(self): +- events = [] +- item1 = self.tv.insert('', 'end', tags=['call']) +- item2 = self.tv.insert('', 'end', tags=['call']) +- self.tv.tag_bind('call', '', +- lambda evt: events.append(1)) +- self.tv.tag_bind('call', '', +- lambda evt: events.append(2)) +- +- self.tv.pack() +- self.tv.wait_visibility() +- self.tv.update() +- +- pos_y = set() +- found = set() +- for i in range(0, 100, 10): +- if len(found) == 2: # item1 and item2 already found +- break +- item_id = self.tv.identify_row(i) +- if item_id and item_id not in found: +- pos_y.add(i) +- found.add(item_id) +- +- self.assertEqual(len(pos_y), 2) # item1 and item2 y pos +- for y in pos_y: +- simulate_mouse_click(self.tv, 0, y) +- +- # by now there should be 4 things in the events list, since each +- # item had a bind for two events that were simulated above +- self.assertEqual(len(events), 4) +- for evt in zip(events[::2], events[1::2]): +- self.assertEqual(evt, (1, 2)) +- +- +- def test_tag_configure(self): +- # Just testing parameter passing for now +- self.assertRaises(TypeError, self.tv.tag_configure) +- self.assertRaises(tkinter.TclError, self.tv.tag_configure, +- 'test', sky='blue') +- self.tv.tag_configure('test', foreground='blue') +- self.assertEqual(str(self.tv.tag_configure('test', 'foreground')), +- 'blue') +- self.assertEqual(str(self.tv.tag_configure('test', foreground=None)), +- 'blue') +- self.assertIsInstance(self.tv.tag_configure('test'), dict) +- +- def test_tag_has(self): +- item1 = self.tv.insert('', 'end', text='Item 1', tags=['tag1']) +- item2 = self.tv.insert('', 'end', text='Item 2', tags=['tag2']) +- self.assertRaises(TypeError, self.tv.tag_has) +- self.assertRaises(TclError, self.tv.tag_has, 'tag1', 'non-existing') +- self.assertTrue(self.tv.tag_has('tag1', item1)) +- self.assertFalse(self.tv.tag_has('tag1', item2)) +- self.assertFalse(self.tv.tag_has('tag2', item1)) +- self.assertTrue(self.tv.tag_has('tag2', item2)) +- self.assertFalse(self.tv.tag_has('tag3', item1)) +- self.assertFalse(self.tv.tag_has('tag3', item2)) +- self.assertEqual(self.tv.tag_has('tag1'), (item1,)) +- self.assertEqual(self.tv.tag_has('tag2'), (item2,)) +- self.assertEqual(self.tv.tag_has('tag3'), ()) +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class SeparatorTest(AbstractWidgetTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'cursor', 'orient', 'style', 'takefocus', +- # 'state'? +- ) +- default_orient = 'horizontal' +- +- def create(self, **kwargs): +- return ttk.Separator(self.root, **kwargs) +- +- +-@add_standard_options(StandardTtkOptionsTests) +-class SizegripTest(AbstractWidgetTest, unittest.TestCase): +- OPTIONS = ( +- 'class', 'cursor', 'style', 'takefocus', +- # 'state'? +- ) +- +- def create(self, **kwargs): +- return ttk.Sizegrip(self.root, **kwargs) +- +-tests_gui = ( +- ButtonTest, CheckbuttonTest, ComboboxTest, EntryTest, +- FrameTest, LabelFrameTest, LabelTest, MenubuttonTest, +- NotebookTest, PanedWindowTest, ProgressbarTest, +- RadiobuttonTest, ScaleTest, ScrollbarTest, SeparatorTest, +- SizegripTest, SpinboxTest, TreeviewTest, WidgetTest, +- ) +- +-if __name__ == "__main__": +- unittest.main() +diff --git a/Lib/tkinter/ttk.py b/Lib/tkinter/ttk.py +deleted file mode 100644 +index 573544dd84..0000000000 ++++ /dev/null +@@ -1,1660 +0,0 @@ +-"""Ttk wrapper. +- +-This module provides classes to allow using Tk themed widget set. +- +-Ttk is based on a revised and enhanced version of +-TIP #48 (http://tip.tcl.tk/48) specified style engine. +- +-Its basic idea is to separate, to the extent possible, the code +-implementing a widget's behavior from the code implementing its +-appearance. Widget class bindings are primarily responsible for +-maintaining the widget state and invoking callbacks, all aspects +-of the widgets appearance lies at Themes. +-""" +- +-__version__ = "0.3.1" +- +-__author__ = "Guilherme Polo " +- +-__all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label", +- "Labelframe", "LabelFrame", "Menubutton", "Notebook", "Panedwindow", +- "PanedWindow", "Progressbar", "Radiobutton", "Scale", "Scrollbar", +- "Separator", "Sizegrip", "Spinbox", "Style", "Treeview", +- # Extensions +- "LabeledScale", "OptionMenu", +- # functions +- "tclobjs_to_py", "setup_master"] +- +-import tkinter +-from tkinter import _flatten, _join, _stringify, _splitdict +- +-# Verify if Tk is new enough to not need the Tile package +-_REQUIRE_TILE = True if tkinter.TkVersion < 8.5 else False +- +-def _load_tile(master): +- if _REQUIRE_TILE: +- import os +- tilelib = os.environ.get('TILE_LIBRARY') +- if tilelib: +- # append custom tile path to the list of directories that +- # Tcl uses when attempting to resolve packages with the package +- # command +- master.tk.eval( +- 'global auto_path; ' +- 'lappend auto_path {%s}' % tilelib) +- +- master.tk.eval('package require tile') # TclError may be raised here +- master._tile_loaded = True +- +-def _format_optvalue(value, script=False): +- """Internal function.""" +- if script: +- # if caller passes a Tcl script to tk.call, all the values need to +- # be grouped into words (arguments to a command in Tcl dialect) +- value = _stringify(value) +- elif isinstance(value, (list, tuple)): +- value = _join(value) +- return value +- +-def _format_optdict(optdict, script=False, ignore=None): +- """Formats optdict to a tuple to pass it to tk.call. +- +- E.g. (script=False): +- {'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns: +- ('-foreground', 'blue', '-padding', '1 2 3 4')""" +- +- opts = [] +- for opt, value in optdict.items(): +- if not ignore or opt not in ignore: +- opts.append("-%s" % opt) +- if value is not None: +- opts.append(_format_optvalue(value, script)) +- +- return _flatten(opts) +- +-def _mapdict_values(items): +- # each value in mapdict is expected to be a sequence, where each item +- # is another sequence containing a state (or several) and a value +- # E.g. (script=False): +- # [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])] +- # returns: +- # ['active selected', 'grey', 'focus', [1, 2, 3, 4]] +- opt_val = [] +- for *state, val in items: +- # hacks for backward compatibility +- state[0] # raise IndexError if empty +- if len(state) == 1: +- # if it is empty (something that evaluates to False), then +- # format it to Tcl code to denote the "normal" state +- state = state[0] or '' +- else: +- # group multiple states +- state = ' '.join(state) # raise TypeError if not str +- opt_val.append(state) +- if val is not None: +- opt_val.append(val) +- return opt_val +- +-def _format_mapdict(mapdict, script=False): +- """Formats mapdict to pass it to tk.call. +- +- E.g. (script=False): +- {'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]} +- +- returns: +- +- ('-expand', '{active selected} grey focus {1, 2, 3, 4}')""" +- +- opts = [] +- for opt, value in mapdict.items(): +- opts.extend(("-%s" % opt, +- _format_optvalue(_mapdict_values(value), script))) +- +- return _flatten(opts) +- +-def _format_elemcreate(etype, script=False, *args, **kw): +- """Formats args and kw according to the given element factory etype.""" +- spec = None +- opts = () +- if etype in ("image", "vsapi"): +- if etype == "image": # define an element based on an image +- # first arg should be the default image name +- iname = args[0] +- # next args, if any, are statespec/value pairs which is almost +- # a mapdict, but we just need the value +- imagespec = _join(_mapdict_values(args[1:])) +- spec = "%s %s" % (iname, imagespec) +- +- else: +- # define an element whose visual appearance is drawn using the +- # Microsoft Visual Styles API which is responsible for the +- # themed styles on Windows XP and Vista. +- # Availability: Tk 8.6, Windows XP and Vista. +- class_name, part_id = args[:2] +- statemap = _join(_mapdict_values(args[2:])) +- spec = "%s %s %s" % (class_name, part_id, statemap) +- +- opts = _format_optdict(kw, script) +- +- elif etype == "from": # clone an element +- # it expects a themename and optionally an element to clone from, +- # otherwise it will clone {} (empty element) +- spec = args[0] # theme name +- if len(args) > 1: # elementfrom specified +- opts = (_format_optvalue(args[1], script),) +- +- if script: +- spec = '{%s}' % spec +- opts = ' '.join(opts) +- +- return spec, opts +- +-def _format_layoutlist(layout, indent=0, indent_size=2): +- """Formats a layout list so we can pass the result to ttk::style +- layout and ttk::style settings. Note that the layout doesn't have to +- be a list necessarily. +- +- E.g.: +- [("Menubutton.background", None), +- ("Menubutton.button", {"children": +- [("Menubutton.focus", {"children": +- [("Menubutton.padding", {"children": +- [("Menubutton.label", {"side": "left", "expand": 1})] +- })] +- })] +- }), +- ("Menubutton.indicator", {"side": "right"}) +- ] +- +- returns: +- +- Menubutton.background +- Menubutton.button -children { +- Menubutton.focus -children { +- Menubutton.padding -children { +- Menubutton.label -side left -expand 1 +- } +- } +- } +- Menubutton.indicator -side right""" +- script = [] +- +- for layout_elem in layout: +- elem, opts = layout_elem +- opts = opts or {} +- fopts = ' '.join(_format_optdict(opts, True, ("children",))) +- head = "%s%s%s" % (' ' * indent, elem, (" %s" % fopts) if fopts else '') +- +- if "children" in opts: +- script.append(head + " -children {") +- indent += indent_size +- newscript, indent = _format_layoutlist(opts['children'], indent, +- indent_size) +- script.append(newscript) +- indent -= indent_size +- script.append('%s}' % (' ' * indent)) +- else: +- script.append(head) +- +- return '\n'.join(script), indent +- +-def _script_from_settings(settings): +- """Returns an appropriate script, based on settings, according to +- theme_settings definition to be used by theme_settings and +- theme_create.""" +- script = [] +- # a script will be generated according to settings passed, which +- # will then be evaluated by Tcl +- for name, opts in settings.items(): +- # will format specific keys according to Tcl code +- if opts.get('configure'): # format 'configure' +- s = ' '.join(_format_optdict(opts['configure'], True)) +- script.append("ttk::style configure %s %s;" % (name, s)) +- +- if opts.get('map'): # format 'map' +- s = ' '.join(_format_mapdict(opts['map'], True)) +- script.append("ttk::style map %s %s;" % (name, s)) +- +- if 'layout' in opts: # format 'layout' which may be empty +- if not opts['layout']: +- s = 'null' # could be any other word, but this one makes sense +- else: +- s, _ = _format_layoutlist(opts['layout']) +- script.append("ttk::style layout %s {\n%s\n}" % (name, s)) +- +- if opts.get('element create'): # format 'element create' +- eopts = opts['element create'] +- etype = eopts[0] +- +- # find where args end, and where kwargs start +- argc = 1 # etype was the first one +- while argc < len(eopts) and not hasattr(eopts[argc], 'items'): +- argc += 1 +- +- elemargs = eopts[1:argc] +- elemkw = eopts[argc] if argc < len(eopts) and eopts[argc] else {} +- spec, opts = _format_elemcreate(etype, True, *elemargs, **elemkw) +- +- script.append("ttk::style element create %s %s %s %s" % ( +- name, etype, spec, opts)) +- +- return '\n'.join(script) +- +-def _list_from_statespec(stuple): +- """Construct a list from the given statespec tuple according to the +- accepted statespec accepted by _format_mapdict.""" +- nval = [] +- for val in stuple: +- typename = getattr(val, 'typename', None) +- if typename is None: +- nval.append(val) +- else: # this is a Tcl object +- val = str(val) +- if typename == 'StateSpec': +- val = val.split() +- nval.append(val) +- +- it = iter(nval) +- return [_flatten(spec) for spec in zip(it, it)] +- +-def _list_from_layouttuple(tk, ltuple): +- """Construct a list from the tuple returned by ttk::layout, this is +- somewhat the reverse of _format_layoutlist.""" +- ltuple = tk.splitlist(ltuple) +- res = [] +- +- indx = 0 +- while indx < len(ltuple): +- name = ltuple[indx] +- opts = {} +- res.append((name, opts)) +- indx += 1 +- +- while indx < len(ltuple): # grab name's options +- opt, val = ltuple[indx:indx + 2] +- if not opt.startswith('-'): # found next name +- break +- +- opt = opt[1:] # remove the '-' from the option +- indx += 2 +- +- if opt == 'children': +- val = _list_from_layouttuple(tk, val) +- +- opts[opt] = val +- +- return res +- +-def _val_or_dict(tk, options, *args): +- """Format options then call Tk command with args and options and return +- the appropriate result. +- +- If no option is specified, a dict is returned. If an option is +- specified with the None value, the value for that option is returned. +- Otherwise, the function just sets the passed options and the caller +- shouldn't be expecting a return value anyway.""" +- options = _format_optdict(options) +- res = tk.call(*(args + options)) +- +- if len(options) % 2: # option specified without a value, return its value +- return res +- +- return _splitdict(tk, res, conv=_tclobj_to_py) +- +-def _convert_stringval(value): +- """Converts a value to, hopefully, a more appropriate Python object.""" +- value = str(value) +- try: +- value = int(value) +- except (ValueError, TypeError): +- pass +- +- return value +- +-def _to_number(x): +- if isinstance(x, str): +- if '.' in x: +- x = float(x) +- else: +- x = int(x) +- return x +- +-def _tclobj_to_py(val): +- """Return value converted from Tcl object to Python object.""" +- if val and hasattr(val, '__len__') and not isinstance(val, str): +- if getattr(val[0], 'typename', None) == 'StateSpec': +- val = _list_from_statespec(val) +- else: +- val = list(map(_convert_stringval, val)) +- +- elif hasattr(val, 'typename'): # some other (single) Tcl object +- val = _convert_stringval(val) +- +- return val +- +-def tclobjs_to_py(adict): +- """Returns adict with its values converted from Tcl objects to Python +- objects.""" +- for opt, val in adict.items(): +- adict[opt] = _tclobj_to_py(val) +- +- return adict +- +-def setup_master(master=None): +- """If master is not None, itself is returned. If master is None, +- the default master is returned if there is one, otherwise a new +- master is created and returned. +- +- If it is not allowed to use the default root and master is None, +- RuntimeError is raised.""" +- if master is None: +- if tkinter._support_default_root: +- master = tkinter._default_root or tkinter.Tk() +- else: +- raise RuntimeError( +- "No master specified and tkinter is " +- "configured to not support default root") +- return master +- +- +-class Style(object): +- """Manipulate style database.""" +- +- _name = "ttk::style" +- +- def __init__(self, master=None): +- master = setup_master(master) +- +- if not getattr(master, '_tile_loaded', False): +- # Load tile now, if needed +- _load_tile(master) +- +- self.master = master +- self.tk = self.master.tk +- +- +- def configure(self, style, query_opt=None, **kw): +- """Query or sets the default value of the specified option(s) in +- style. +- +- Each key in kw is an option and each value is either a string or +- a sequence identifying the value for that option.""" +- if query_opt is not None: +- kw[query_opt] = None +- result = _val_or_dict(self.tk, kw, self._name, "configure", style) +- if result or query_opt: +- return result +- +- +- def map(self, style, query_opt=None, **kw): +- """Query or sets dynamic values of the specified option(s) in +- style. +- +- Each key in kw is an option and each value should be a list or a +- tuple (usually) containing statespecs grouped in tuples, or list, +- or something else of your preference. A statespec is compound of +- one or more states and then a value.""" +- if query_opt is not None: +- return _list_from_statespec(self.tk.splitlist( +- self.tk.call(self._name, "map", style, '-%s' % query_opt))) +- +- return _splitdict( +- self.tk, +- self.tk.call(self._name, "map", style, *_format_mapdict(kw)), +- conv=_tclobj_to_py) +- +- +- def lookup(self, style, option, state=None, default=None): +- """Returns the value specified for option in style. +- +- If state is specified it is expected to be a sequence of one +- or more states. If the default argument is set, it is used as +- a fallback value in case no specification for option is found.""" +- state = ' '.join(state) if state else '' +- +- return self.tk.call(self._name, "lookup", style, '-%s' % option, +- state, default) +- +- +- def layout(self, style, layoutspec=None): +- """Define the widget layout for given style. If layoutspec is +- omitted, return the layout specification for given style. +- +- layoutspec is expected to be a list or an object different than +- None that evaluates to False if you want to "turn off" that style. +- If it is a list (or tuple, or something else), each item should be +- a tuple where the first item is the layout name and the second item +- should have the format described below: +- +- LAYOUTS +- +- A layout can contain the value None, if takes no options, or +- a dict of options specifying how to arrange the element. +- The layout mechanism uses a simplified version of the pack +- geometry manager: given an initial cavity, each element is +- allocated a parcel. Valid options/values are: +- +- side: whichside +- Specifies which side of the cavity to place the +- element; one of top, right, bottom or left. If +- omitted, the element occupies the entire cavity. +- +- sticky: nswe +- Specifies where the element is placed inside its +- allocated parcel. +- +- children: [sublayout... ] +- Specifies a list of elements to place inside the +- element. Each element is a tuple (or other sequence) +- where the first item is the layout name, and the other +- is a LAYOUT.""" +- lspec = None +- if layoutspec: +- lspec = _format_layoutlist(layoutspec)[0] +- elif layoutspec is not None: # will disable the layout ({}, '', etc) +- lspec = "null" # could be any other word, but this may make sense +- # when calling layout(style) later +- +- return _list_from_layouttuple(self.tk, +- self.tk.call(self._name, "layout", style, lspec)) +- +- +- def element_create(self, elementname, etype, *args, **kw): +- """Create a new element in the current theme of given etype.""" +- spec, opts = _format_elemcreate(etype, False, *args, **kw) +- self.tk.call(self._name, "element", "create", elementname, etype, +- spec, *opts) +- +- +- def element_names(self): +- """Returns the list of elements defined in the current theme.""" +- return tuple(n.lstrip('-') for n in self.tk.splitlist( +- self.tk.call(self._name, "element", "names"))) +- +- +- def element_options(self, elementname): +- """Return the list of elementname's options.""" +- return tuple(o.lstrip('-') for o in self.tk.splitlist( +- self.tk.call(self._name, "element", "options", elementname))) +- +- +- def theme_create(self, themename, parent=None, settings=None): +- """Creates a new theme. +- +- It is an error if themename already exists. If parent is +- specified, the new theme will inherit styles, elements and +- layouts from the specified parent theme. If settings are present, +- they are expected to have the same syntax used for theme_settings.""" +- script = _script_from_settings(settings) if settings else '' +- +- if parent: +- self.tk.call(self._name, "theme", "create", themename, +- "-parent", parent, "-settings", script) +- else: +- self.tk.call(self._name, "theme", "create", themename, +- "-settings", script) +- +- +- def theme_settings(self, themename, settings): +- """Temporarily sets the current theme to themename, apply specified +- settings and then restore the previous theme. +- +- Each key in settings is a style and each value may contain the +- keys 'configure', 'map', 'layout' and 'element create' and they +- are expected to have the same format as specified by the methods +- configure, map, layout and element_create respectively.""" +- script = _script_from_settings(settings) +- self.tk.call(self._name, "theme", "settings", themename, script) +- +- +- def theme_names(self): +- """Returns a list of all known themes.""" +- return self.tk.splitlist(self.tk.call(self._name, "theme", "names")) +- +- +- def theme_use(self, themename=None): +- """If themename is None, returns the theme in use, otherwise, set +- the current theme to themename, refreshes all widgets and emits +- a <> event.""" +- if themename is None: +- # Starting on Tk 8.6, checking this global is no longer needed +- # since it allows doing self.tk.call(self._name, "theme", "use") +- return self.tk.eval("return $ttk::currentTheme") +- +- # using "ttk::setTheme" instead of "ttk::style theme use" causes +- # the variable currentTheme to be updated, also, ttk::setTheme calls +- # "ttk::style theme use" in order to change theme. +- self.tk.call("ttk::setTheme", themename) +- +- +-class Widget(tkinter.Widget): +- """Base class for Tk themed widgets.""" +- +- def __init__(self, master, widgetname, kw=None): +- """Constructs a Ttk Widget with the parent master. +- +- STANDARD OPTIONS +- +- class, cursor, takefocus, style +- +- SCROLLABLE WIDGET OPTIONS +- +- xscrollcommand, yscrollcommand +- +- LABEL WIDGET OPTIONS +- +- text, textvariable, underline, image, compound, width +- +- WIDGET STATES +- +- active, disabled, focus, pressed, selected, background, +- readonly, alternate, invalid +- """ +- master = setup_master(master) +- if not getattr(master, '_tile_loaded', False): +- # Load tile now, if needed +- _load_tile(master) +- tkinter.Widget.__init__(self, master, widgetname, kw=kw) +- +- +- def identify(self, x, y): +- """Returns the name of the element at position x, y, or the empty +- string if the point does not lie within any element. +- +- x and y are pixel coordinates relative to the widget.""" +- return self.tk.call(self._w, "identify", x, y) +- +- +- def instate(self, statespec, callback=None, *args, **kw): +- """Test the widget's state. +- +- If callback is not specified, returns True if the widget state +- matches statespec and False otherwise. If callback is specified, +- then it will be invoked with *args, **kw if the widget state +- matches statespec. statespec is expected to be a sequence.""" +- ret = self.tk.getboolean( +- self.tk.call(self._w, "instate", ' '.join(statespec))) +- if ret and callback: +- return callback(*args, **kw) +- +- return ret +- +- +- def state(self, statespec=None): +- """Modify or inquire widget state. +- +- Widget state is returned if statespec is None, otherwise it is +- set according to the statespec flags and then a new state spec +- is returned indicating which flags were changed. statespec is +- expected to be a sequence.""" +- if statespec is not None: +- statespec = ' '.join(statespec) +- +- return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec))) +- +- +-class Button(Widget): +- """Ttk Button widget, displays a textual label and/or image, and +- evaluates a command when pressed.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Button widget with the parent master. +- +- STANDARD OPTIONS +- +- class, compound, cursor, image, state, style, takefocus, +- text, textvariable, underline, width +- +- WIDGET-SPECIFIC OPTIONS +- +- command, default, width +- """ +- Widget.__init__(self, master, "ttk::button", kw) +- +- +- def invoke(self): +- """Invokes the command associated with the button.""" +- return self.tk.call(self._w, "invoke") +- +- +-class Checkbutton(Widget): +- """Ttk Checkbutton widget which is either in on- or off-state.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Checkbutton widget with the parent master. +- +- STANDARD OPTIONS +- +- class, compound, cursor, image, state, style, takefocus, +- text, textvariable, underline, width +- +- WIDGET-SPECIFIC OPTIONS +- +- command, offvalue, onvalue, variable +- """ +- Widget.__init__(self, master, "ttk::checkbutton", kw) +- +- +- def invoke(self): +- """Toggles between the selected and deselected states and +- invokes the associated command. If the widget is currently +- selected, sets the option variable to the offvalue option +- and deselects the widget; otherwise, sets the option variable +- to the option onvalue. +- +- Returns the result of the associated command.""" +- return self.tk.call(self._w, "invoke") +- +- +-class Entry(Widget, tkinter.Entry): +- """Ttk Entry widget displays a one-line text string and allows that +- string to be edited by the user.""" +- +- def __init__(self, master=None, widget=None, **kw): +- """Constructs a Ttk Entry widget with the parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus, xscrollcommand +- +- WIDGET-SPECIFIC OPTIONS +- +- exportselection, invalidcommand, justify, show, state, +- textvariable, validate, validatecommand, width +- +- VALIDATION MODES +- +- none, key, focus, focusin, focusout, all +- """ +- Widget.__init__(self, master, widget or "ttk::entry", kw) +- +- +- def bbox(self, index): +- """Return a tuple of (x, y, width, height) which describes the +- bounding box of the character given by index.""" +- return self._getints(self.tk.call(self._w, "bbox", index)) +- +- +- def identify(self, x, y): +- """Returns the name of the element at position x, y, or the +- empty string if the coordinates are outside the window.""" +- return self.tk.call(self._w, "identify", x, y) +- +- +- def validate(self): +- """Force revalidation, independent of the conditions specified +- by the validate option. Returns False if validation fails, True +- if it succeeds. Sets or clears the invalid state accordingly.""" +- return self.tk.getboolean(self.tk.call(self._w, "validate")) +- +- +-class Combobox(Entry): +- """Ttk Combobox widget combines a text field with a pop-down list of +- values.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Combobox widget with the parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus +- +- WIDGET-SPECIFIC OPTIONS +- +- exportselection, justify, height, postcommand, state, +- textvariable, values, width +- """ +- Entry.__init__(self, master, "ttk::combobox", **kw) +- +- +- def current(self, newindex=None): +- """If newindex is supplied, sets the combobox value to the +- element at position newindex in the list of values. Otherwise, +- returns the index of the current value in the list of values +- or -1 if the current value does not appear in the list.""" +- if newindex is None: +- return self.tk.getint(self.tk.call(self._w, "current")) +- return self.tk.call(self._w, "current", newindex) +- +- +- def set(self, value): +- """Sets the value of the combobox to value.""" +- self.tk.call(self._w, "set", value) +- +- +-class Frame(Widget): +- """Ttk Frame widget is a container, used to group other widgets +- together.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Frame with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus +- +- WIDGET-SPECIFIC OPTIONS +- +- borderwidth, relief, padding, width, height +- """ +- Widget.__init__(self, master, "ttk::frame", kw) +- +- +-class Label(Widget): +- """Ttk Label widget displays a textual label and/or image.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Label with parent master. +- +- STANDARD OPTIONS +- +- class, compound, cursor, image, style, takefocus, text, +- textvariable, underline, width +- +- WIDGET-SPECIFIC OPTIONS +- +- anchor, background, font, foreground, justify, padding, +- relief, text, wraplength +- """ +- Widget.__init__(self, master, "ttk::label", kw) +- +- +-class Labelframe(Widget): +- """Ttk Labelframe widget is a container used to group other widgets +- together. It has an optional label, which may be a plain text string +- or another widget.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Labelframe with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus +- +- WIDGET-SPECIFIC OPTIONS +- labelanchor, text, underline, padding, labelwidget, width, +- height +- """ +- Widget.__init__(self, master, "ttk::labelframe", kw) +- +-LabelFrame = Labelframe # tkinter name compatibility +- +- +-class Menubutton(Widget): +- """Ttk Menubutton widget displays a textual label and/or image, and +- displays a menu when pressed.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Menubutton with parent master. +- +- STANDARD OPTIONS +- +- class, compound, cursor, image, state, style, takefocus, +- text, textvariable, underline, width +- +- WIDGET-SPECIFIC OPTIONS +- +- direction, menu +- """ +- Widget.__init__(self, master, "ttk::menubutton", kw) +- +- +-class Notebook(Widget): +- """Ttk Notebook widget manages a collection of windows and displays +- a single one at a time. Each child window is associated with a tab, +- which the user may select to change the currently-displayed window.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Notebook with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus +- +- WIDGET-SPECIFIC OPTIONS +- +- height, padding, width +- +- TAB OPTIONS +- +- state, sticky, padding, text, image, compound, underline +- +- TAB IDENTIFIERS (tab_id) +- +- The tab_id argument found in several methods may take any of +- the following forms: +- +- * An integer between zero and the number of tabs +- * The name of a child window +- * A positional specification of the form "@x,y", which +- defines the tab +- * The string "current", which identifies the +- currently-selected tab +- * The string "end", which returns the number of tabs (only +- valid for method index) +- """ +- Widget.__init__(self, master, "ttk::notebook", kw) +- +- +- def add(self, child, **kw): +- """Adds a new tab to the notebook. +- +- If window is currently managed by the notebook but hidden, it is +- restored to its previous position.""" +- self.tk.call(self._w, "add", child, *(_format_optdict(kw))) +- +- +- def forget(self, tab_id): +- """Removes the tab specified by tab_id, unmaps and unmanages the +- associated window.""" +- self.tk.call(self._w, "forget", tab_id) +- +- +- def hide(self, tab_id): +- """Hides the tab specified by tab_id. +- +- The tab will not be displayed, but the associated window remains +- managed by the notebook and its configuration remembered. Hidden +- tabs may be restored with the add command.""" +- self.tk.call(self._w, "hide", tab_id) +- +- +- def identify(self, x, y): +- """Returns the name of the tab element at position x, y, or the +- empty string if none.""" +- return self.tk.call(self._w, "identify", x, y) +- +- +- def index(self, tab_id): +- """Returns the numeric index of the tab specified by tab_id, or +- the total number of tabs if tab_id is the string "end".""" +- return self.tk.getint(self.tk.call(self._w, "index", tab_id)) +- +- +- def insert(self, pos, child, **kw): +- """Inserts a pane at the specified position. +- +- pos is either the string end, an integer index, or the name of +- a managed child. If child is already managed by the notebook, +- moves it to the specified position.""" +- self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw))) +- +- +- def select(self, tab_id=None): +- """Selects the specified tab. +- +- The associated child window will be displayed, and the +- previously-selected window (if different) is unmapped. If tab_id +- is omitted, returns the widget name of the currently selected +- pane.""" +- return self.tk.call(self._w, "select", tab_id) +- +- +- def tab(self, tab_id, option=None, **kw): +- """Query or modify the options of the specific tab_id. +- +- If kw is not given, returns a dict of the tab option values. If option +- is specified, returns the value of that option. Otherwise, sets the +- options to the corresponding values.""" +- if option is not None: +- kw[option] = None +- return _val_or_dict(self.tk, kw, self._w, "tab", tab_id) +- +- +- def tabs(self): +- """Returns a list of windows managed by the notebook.""" +- return self.tk.splitlist(self.tk.call(self._w, "tabs") or ()) +- +- +- def enable_traversal(self): +- """Enable keyboard traversal for a toplevel window containing +- this notebook. +- +- This will extend the bindings for the toplevel window containing +- this notebook as follows: +- +- Control-Tab: selects the tab following the currently selected +- one +- +- Shift-Control-Tab: selects the tab preceding the currently +- selected one +- +- Alt-K: where K is the mnemonic (underlined) character of any +- tab, will select that tab. +- +- Multiple notebooks in a single toplevel may be enabled for +- traversal, including nested notebooks. However, notebook traversal +- only works properly if all panes are direct children of the +- notebook.""" +- # The only, and good, difference I see is about mnemonics, which works +- # after calling this method. Control-Tab and Shift-Control-Tab always +- # works (here at least). +- self.tk.call("ttk::notebook::enableTraversal", self._w) +- +- +-class Panedwindow(Widget, tkinter.PanedWindow): +- """Ttk Panedwindow widget displays a number of subwindows, stacked +- either vertically or horizontally.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Panedwindow with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus +- +- WIDGET-SPECIFIC OPTIONS +- +- orient, width, height +- +- PANE OPTIONS +- +- weight +- """ +- Widget.__init__(self, master, "ttk::panedwindow", kw) +- +- +- forget = tkinter.PanedWindow.forget # overrides Pack.forget +- +- +- def insert(self, pos, child, **kw): +- """Inserts a pane at the specified positions. +- +- pos is either the string end, and integer index, or the name +- of a child. If child is already managed by the paned window, +- moves it to the specified position.""" +- self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw))) +- +- +- def pane(self, pane, option=None, **kw): +- """Query or modify the options of the specified pane. +- +- pane is either an integer index or the name of a managed subwindow. +- If kw is not given, returns a dict of the pane option values. If +- option is specified then the value for that option is returned. +- Otherwise, sets the options to the corresponding values.""" +- if option is not None: +- kw[option] = None +- return _val_or_dict(self.tk, kw, self._w, "pane", pane) +- +- +- def sashpos(self, index, newpos=None): +- """If newpos is specified, sets the position of sash number index. +- +- May adjust the positions of adjacent sashes to ensure that +- positions are monotonically increasing. Sash positions are further +- constrained to be between 0 and the total size of the widget. +- +- Returns the new position of sash number index.""" +- return self.tk.getint(self.tk.call(self._w, "sashpos", index, newpos)) +- +-PanedWindow = Panedwindow # tkinter name compatibility +- +- +-class Progressbar(Widget): +- """Ttk Progressbar widget shows the status of a long-running +- operation. They can operate in two modes: determinate mode shows the +- amount completed relative to the total amount of work to be done, and +- indeterminate mode provides an animated display to let the user know +- that something is happening.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Progressbar with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus +- +- WIDGET-SPECIFIC OPTIONS +- +- orient, length, mode, maximum, value, variable, phase +- """ +- Widget.__init__(self, master, "ttk::progressbar", kw) +- +- +- def start(self, interval=None): +- """Begin autoincrement mode: schedules a recurring timer event +- that calls method step every interval milliseconds. +- +- interval defaults to 50 milliseconds (20 steps/second) if omitted.""" +- self.tk.call(self._w, "start", interval) +- +- +- def step(self, amount=None): +- """Increments the value option by amount. +- +- amount defaults to 1.0 if omitted.""" +- self.tk.call(self._w, "step", amount) +- +- +- def stop(self): +- """Stop autoincrement mode: cancels any recurring timer event +- initiated by start.""" +- self.tk.call(self._w, "stop") +- +- +-class Radiobutton(Widget): +- """Ttk Radiobutton widgets are used in groups to show or change a +- set of mutually-exclusive options.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Radiobutton with parent master. +- +- STANDARD OPTIONS +- +- class, compound, cursor, image, state, style, takefocus, +- text, textvariable, underline, width +- +- WIDGET-SPECIFIC OPTIONS +- +- command, value, variable +- """ +- Widget.__init__(self, master, "ttk::radiobutton", kw) +- +- +- def invoke(self): +- """Sets the option variable to the option value, selects the +- widget, and invokes the associated command. +- +- Returns the result of the command, or an empty string if +- no command is specified.""" +- return self.tk.call(self._w, "invoke") +- +- +-class Scale(Widget, tkinter.Scale): +- """Ttk Scale widget is typically used to control the numeric value of +- a linked variable that varies uniformly over some range.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Scale with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus +- +- WIDGET-SPECIFIC OPTIONS +- +- command, from, length, orient, to, value, variable +- """ +- Widget.__init__(self, master, "ttk::scale", kw) +- +- +- def configure(self, cnf=None, **kw): +- """Modify or query scale options. +- +- Setting a value for any of the "from", "from_" or "to" options +- generates a <> event.""" +- if cnf: +- kw.update(cnf) +- Widget.configure(self, **kw) +- if any(['from' in kw, 'from_' in kw, 'to' in kw]): +- self.event_generate('<>') +- +- +- def get(self, x=None, y=None): +- """Get the current value of the value option, or the value +- corresponding to the coordinates x, y if they are specified. +- +- x and y are pixel coordinates relative to the scale widget +- origin.""" +- return self.tk.call(self._w, 'get', x, y) +- +- +-class Scrollbar(Widget, tkinter.Scrollbar): +- """Ttk Scrollbar controls the viewport of a scrollable widget.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Scrollbar with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus +- +- WIDGET-SPECIFIC OPTIONS +- +- command, orient +- """ +- Widget.__init__(self, master, "ttk::scrollbar", kw) +- +- +-class Separator(Widget): +- """Ttk Separator widget displays a horizontal or vertical separator +- bar.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Separator with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus +- +- WIDGET-SPECIFIC OPTIONS +- +- orient +- """ +- Widget.__init__(self, master, "ttk::separator", kw) +- +- +-class Sizegrip(Widget): +- """Ttk Sizegrip allows the user to resize the containing toplevel +- window by pressing and dragging the grip.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Sizegrip with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, state, style, takefocus +- """ +- Widget.__init__(self, master, "ttk::sizegrip", kw) +- +- +-class Spinbox(Entry): +- """Ttk Spinbox is an Entry with increment and decrement arrows +- +- It is commonly used for number entry or to select from a list of +- string values. +- """ +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Spinbox widget with the parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus, validate, +- validatecommand, xscrollcommand, invalidcommand +- +- WIDGET-SPECIFIC OPTIONS +- +- to, from_, increment, values, wrap, format, command +- """ +- Entry.__init__(self, master, "ttk::spinbox", **kw) +- +- +- def set(self, value): +- """Sets the value of the Spinbox to value.""" +- self.tk.call(self._w, "set", value) +- +- +-class Treeview(Widget, tkinter.XView, tkinter.YView): +- """Ttk Treeview widget displays a hierarchical collection of items. +- +- Each item has a textual label, an optional image, and an optional list +- of data values. The data values are displayed in successive columns +- after the tree label.""" +- +- def __init__(self, master=None, **kw): +- """Construct a Ttk Treeview with parent master. +- +- STANDARD OPTIONS +- +- class, cursor, style, takefocus, xscrollcommand, +- yscrollcommand +- +- WIDGET-SPECIFIC OPTIONS +- +- columns, displaycolumns, height, padding, selectmode, show +- +- ITEM OPTIONS +- +- text, image, values, open, tags +- +- TAG OPTIONS +- +- foreground, background, font, image +- """ +- Widget.__init__(self, master, "ttk::treeview", kw) +- +- +- def bbox(self, item, column=None): +- """Returns the bounding box (relative to the treeview widget's +- window) of the specified item in the form x y width height. +- +- If column is specified, returns the bounding box of that cell. +- If the item is not visible (i.e., if it is a descendant of a +- closed item or is scrolled offscreen), returns an empty string.""" +- return self._getints(self.tk.call(self._w, "bbox", item, column)) or '' +- +- +- def get_children(self, item=None): +- """Returns a tuple of children belonging to item. +- +- If item is not specified, returns root children.""" +- return self.tk.splitlist( +- self.tk.call(self._w, "children", item or '') or ()) +- +- +- def set_children(self, item, *newchildren): +- """Replaces item's child with newchildren. +- +- Children present in item that are not present in newchildren +- are detached from tree. No items in newchildren may be an +- ancestor of item.""" +- self.tk.call(self._w, "children", item, newchildren) +- +- +- def column(self, column, option=None, **kw): +- """Query or modify the options for the specified column. +- +- If kw is not given, returns a dict of the column option values. If +- option is specified then the value for that option is returned. +- Otherwise, sets the options to the corresponding values.""" +- if option is not None: +- kw[option] = None +- return _val_or_dict(self.tk, kw, self._w, "column", column) +- +- +- def delete(self, *items): +- """Delete all specified items and all their descendants. The root +- item may not be deleted.""" +- self.tk.call(self._w, "delete", items) +- +- +- def detach(self, *items): +- """Unlinks all of the specified items from the tree. +- +- The items and all of their descendants are still present, and may +- be reinserted at another point in the tree, but will not be +- displayed. The root item may not be detached.""" +- self.tk.call(self._w, "detach", items) +- +- +- def exists(self, item): +- """Returns True if the specified item is present in the tree, +- False otherwise.""" +- return self.tk.getboolean(self.tk.call(self._w, "exists", item)) +- +- +- def focus(self, item=None): +- """If item is specified, sets the focus item to item. Otherwise, +- returns the current focus item, or '' if there is none.""" +- return self.tk.call(self._w, "focus", item) +- +- +- def heading(self, column, option=None, **kw): +- """Query or modify the heading options for the specified column. +- +- If kw is not given, returns a dict of the heading option values. If +- option is specified then the value for that option is returned. +- Otherwise, sets the options to the corresponding values. +- +- Valid options/values are: +- text: text +- The text to display in the column heading +- image: image_name +- Specifies an image to display to the right of the column +- heading +- anchor: anchor +- Specifies how the heading text should be aligned. One of +- the standard Tk anchor values +- command: callback +- A callback to be invoked when the heading label is +- pressed. +- +- To configure the tree column heading, call this with column = "#0" """ +- cmd = kw.get('command') +- if cmd and not isinstance(cmd, str): +- # callback not registered yet, do it now +- kw['command'] = self.master.register(cmd, self._substitute) +- +- if option is not None: +- kw[option] = None +- +- return _val_or_dict(self.tk, kw, self._w, 'heading', column) +- +- +- def identify(self, component, x, y): +- """Returns a description of the specified component under the +- point given by x and y, or the empty string if no such component +- is present at that position.""" +- return self.tk.call(self._w, "identify", component, x, y) +- +- +- def identify_row(self, y): +- """Returns the item ID of the item at position y.""" +- return self.identify("row", 0, y) +- +- +- def identify_column(self, x): +- """Returns the data column identifier of the cell at position x. +- +- The tree column has ID #0.""" +- return self.identify("column", x, 0) +- +- +- def identify_region(self, x, y): +- """Returns one of: +- +- heading: Tree heading area. +- separator: Space between two columns headings; +- tree: The tree area. +- cell: A data cell. +- +- * Availability: Tk 8.6""" +- return self.identify("region", x, y) +- +- +- def identify_element(self, x, y): +- """Returns the element at position x, y. +- +- * Availability: Tk 8.6""" +- return self.identify("element", x, y) +- +- +- def index(self, item): +- """Returns the integer index of item within its parent's list +- of children.""" +- return self.tk.getint(self.tk.call(self._w, "index", item)) +- +- +- def insert(self, parent, index, iid=None, **kw): +- """Creates a new item and return the item identifier of the newly +- created item. +- +- parent is the item ID of the parent item, or the empty string +- to create a new top-level item. index is an integer, or the value +- end, specifying where in the list of parent's children to insert +- the new item. If index is less than or equal to zero, the new node +- is inserted at the beginning, if index is greater than or equal to +- the current number of children, it is inserted at the end. If iid +- is specified, it is used as the item identifier, iid must not +- already exist in the tree. Otherwise, a new unique identifier +- is generated.""" +- opts = _format_optdict(kw) +- if iid is not None: +- res = self.tk.call(self._w, "insert", parent, index, +- "-id", iid, *opts) +- else: +- res = self.tk.call(self._w, "insert", parent, index, *opts) +- +- return res +- +- +- def item(self, item, option=None, **kw): +- """Query or modify the options for the specified item. +- +- If no options are given, a dict with options/values for the item +- is returned. If option is specified then the value for that option +- is returned. Otherwise, sets the options to the corresponding +- values as given by kw.""" +- if option is not None: +- kw[option] = None +- return _val_or_dict(self.tk, kw, self._w, "item", item) +- +- +- def move(self, item, parent, index): +- """Moves item to position index in parent's list of children. +- +- It is illegal to move an item under one of its descendants. If +- index is less than or equal to zero, item is moved to the +- beginning, if greater than or equal to the number of children, +- it is moved to the end. If item was detached it is reattached.""" +- self.tk.call(self._w, "move", item, parent, index) +- +- reattach = move # A sensible method name for reattaching detached items +- +- +- def next(self, item): +- """Returns the identifier of item's next sibling, or '' if item +- is the last child of its parent.""" +- return self.tk.call(self._w, "next", item) +- +- +- def parent(self, item): +- """Returns the ID of the parent of item, or '' if item is at the +- top level of the hierarchy.""" +- return self.tk.call(self._w, "parent", item) +- +- +- def prev(self, item): +- """Returns the identifier of item's previous sibling, or '' if +- item is the first child of its parent.""" +- return self.tk.call(self._w, "prev", item) +- +- +- def see(self, item): +- """Ensure that item is visible. +- +- Sets all of item's ancestors open option to True, and scrolls +- the widget if necessary so that item is within the visible +- portion of the tree.""" +- self.tk.call(self._w, "see", item) +- +- +- def selection(self): +- """Returns the tuple of selected items.""" +- return self.tk.splitlist(self.tk.call(self._w, "selection")) +- +- +- def _selection(self, selop, items): +- if len(items) == 1 and isinstance(items[0], (tuple, list)): +- items = items[0] +- +- self.tk.call(self._w, "selection", selop, items) +- +- +- def selection_set(self, *items): +- """The specified items becomes the new selection.""" +- self._selection("set", items) +- +- +- def selection_add(self, *items): +- """Add all of the specified items to the selection.""" +- self._selection("add", items) +- +- +- def selection_remove(self, *items): +- """Remove all of the specified items from the selection.""" +- self._selection("remove", items) +- +- +- def selection_toggle(self, *items): +- """Toggle the selection state of each specified item.""" +- self._selection("toggle", items) +- +- +- def set(self, item, column=None, value=None): +- """Query or set the value of given item. +- +- With one argument, return a dictionary of column/value pairs +- for the specified item. With two arguments, return the current +- value of the specified column. With three arguments, set the +- value of given column in given item to the specified value.""" +- res = self.tk.call(self._w, "set", item, column, value) +- if column is None and value is None: +- return _splitdict(self.tk, res, +- cut_minus=False, conv=_tclobj_to_py) +- else: +- return res +- +- +- def tag_bind(self, tagname, sequence=None, callback=None): +- """Bind a callback for the given event sequence to the tag tagname. +- When an event is delivered to an item, the callbacks for each +- of the item's tags option are called.""" +- self._bind((self._w, "tag", "bind", tagname), sequence, callback, add=0) +- +- +- def tag_configure(self, tagname, option=None, **kw): +- """Query or modify the options for the specified tagname. +- +- If kw is not given, returns a dict of the option settings for tagname. +- If option is specified, returns the value for that option for the +- specified tagname. Otherwise, sets the options to the corresponding +- values for the given tagname.""" +- if option is not None: +- kw[option] = None +- return _val_or_dict(self.tk, kw, self._w, "tag", "configure", +- tagname) +- +- +- def tag_has(self, tagname, item=None): +- """If item is specified, returns 1 or 0 depending on whether the +- specified item has the given tagname. Otherwise, returns a list of +- all items which have the specified tag. +- +- * Availability: Tk 8.6""" +- if item is None: +- return self.tk.splitlist( +- self.tk.call(self._w, "tag", "has", tagname)) +- else: +- return self.tk.getboolean( +- self.tk.call(self._w, "tag", "has", tagname, item)) +- +- +-# Extensions +- +-class LabeledScale(Frame): +- """A Ttk Scale widget with a Ttk Label widget indicating its +- current value. +- +- The Ttk Scale can be accessed through instance.scale, and Ttk Label +- can be accessed through instance.label""" +- +- def __init__(self, master=None, variable=None, from_=0, to=10, **kw): +- """Construct a horizontal LabeledScale with parent master, a +- variable to be associated with the Ttk Scale widget and its range. +- If variable is not specified, a tkinter.IntVar is created. +- +- WIDGET-SPECIFIC OPTIONS +- +- compound: 'top' or 'bottom' +- Specifies how to display the label relative to the scale. +- Defaults to 'top'. +- """ +- self._label_top = kw.pop('compound', 'top') == 'top' +- +- Frame.__init__(self, master, **kw) +- self._variable = variable or tkinter.IntVar(master) +- self._variable.set(from_) +- self._last_valid = from_ +- +- self.label = Label(self) +- self.scale = Scale(self, variable=self._variable, from_=from_, to=to) +- self.scale.bind('<>', self._adjust) +- +- # position scale and label according to the compound option +- scale_side = 'bottom' if self._label_top else 'top' +- label_side = 'top' if scale_side == 'bottom' else 'bottom' +- self.scale.pack(side=scale_side, fill='x') +- tmp = Label(self).pack(side=label_side) # place holder +- self.label.place(anchor='n' if label_side == 'top' else 's') +- +- # update the label as scale or variable changes +- self.__tracecb = self._variable.trace_variable('w', self._adjust) +- self.bind('', self._adjust) +- self.bind('', self._adjust) +- +- +- def destroy(self): +- """Destroy this widget and possibly its associated variable.""" +- try: +- self._variable.trace_vdelete('w', self.__tracecb) +- except AttributeError: +- pass +- else: +- del self._variable +- super().destroy() +- self.label = None +- self.scale = None +- +- +- def _adjust(self, *args): +- """Adjust the label position according to the scale.""" +- def adjust_label(): +- self.update_idletasks() # "force" scale redraw +- +- x, y = self.scale.coords() +- if self._label_top: +- y = self.scale.winfo_y() - self.label.winfo_reqheight() +- else: +- y = self.scale.winfo_reqheight() + self.label.winfo_reqheight() +- +- self.label.place_configure(x=x, y=y) +- +- from_ = _to_number(self.scale['from']) +- to = _to_number(self.scale['to']) +- if to < from_: +- from_, to = to, from_ +- newval = self._variable.get() +- if not from_ <= newval <= to: +- # value outside range, set value back to the last valid one +- self.value = self._last_valid +- return +- +- self._last_valid = newval +- self.label['text'] = newval +- self.after_idle(adjust_label) +- +- @property +- def value(self): +- """Return current scale value.""" +- return self._variable.get() +- +- @value.setter +- def value(self, val): +- """Set new scale value.""" +- self._variable.set(val) +- +- +-class OptionMenu(Menubutton): +- """Themed OptionMenu, based after tkinter's OptionMenu, which allows +- the user to select a value from a menu.""" +- +- def __init__(self, master, variable, default=None, *values, **kwargs): +- """Construct a themed OptionMenu widget with master as the parent, +- the resource textvariable set to variable, the initially selected +- value specified by the default parameter, the menu values given by +- *values and additional keywords. +- +- WIDGET-SPECIFIC OPTIONS +- +- style: stylename +- Menubutton style. +- direction: 'above', 'below', 'left', 'right', or 'flush' +- Menubutton direction. +- command: callback +- A callback that will be invoked after selecting an item. +- """ +- kw = {'textvariable': variable, 'style': kwargs.pop('style', None), +- 'direction': kwargs.pop('direction', None)} +- Menubutton.__init__(self, master, **kw) +- self['menu'] = tkinter.Menu(self, tearoff=False) +- +- self._variable = variable +- self._callback = kwargs.pop('command', None) +- if kwargs: +- raise tkinter.TclError('unknown option -%s' % ( +- next(iter(kwargs.keys())))) +- +- self.set_menu(default, *values) +- +- +- def __getitem__(self, item): +- if item == 'menu': +- return self.nametowidget(Menubutton.__getitem__(self, item)) +- +- return Menubutton.__getitem__(self, item) +- +- +- def set_menu(self, default=None, *values): +- """Build a new menu of radiobuttons with *values and optionally +- a default value.""" +- menu = self['menu'] +- menu.delete(0, 'end') +- for val in values: +- menu.add_radiobutton(label=val, +- command=tkinter._setit(self._variable, val, self._callback), +- variable=self._variable) +- +- if default: +- self._variable.set(default) +- +- +- def destroy(self): +- """Destroy this widget and its associated variable.""" +- try: +- del self._variable +- except AttributeError: +- pass +- super().destroy() +diff --git a/Lib/tokenize.py b/Lib/tokenize.py +index d426cd2df5..6c857f8547 100644 +--- a/Lib/tokenize.py ++++ b/Lib/tokenize.py +@@ -306,8 +306,15 @@ def generate_tokens(readline): + contline = None + indents = [0] + ++ last_line = b'' ++ line = b'' + while 1: # loop over lines in stream + try: ++ # We capture the value of the line variable here because ++ # readline uses the empty string '' to signal end of input, ++ # hence `line` itself will always be overwritten at the end ++ # of this loop. ++ last_line = line + line = readline() + except StopIteration: + line = '' +@@ -437,6 +444,9 @@ def generate_tokens(readline): + (lnum, pos), (lnum, pos+1), line) + pos += 1 + ++ # Add an implicit NEWLINE if the input doesn't end in one ++ if last_line and last_line[-1] not in '\r\n': ++ yield (NEWLINE, '', (lnum - 1, len(last_line)), (lnum - 1, len(last_line) + 1), '') + for indent in indents[1:]: # pop remaining indent levels + yield (DEDENT, '', (lnum, 0), (lnum, 0), '') + yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '') +diff --git a/Lib/uuid.py b/Lib/uuid.py +index 618bc6385c..80d33c0bd8 100644 +--- a/Lib/uuid.py ++++ b/Lib/uuid.py +@@ -419,7 +419,7 @@ def _ipconfig_getnode(): + with pipe: + for line in pipe: + value = line.split(':')[-1].strip().lower() +- if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value): ++ if re.match('(?:[0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]$', value): + return int(value.replace('-', ''), 16) + + def _netbios_getnode(): +@@ -522,6 +522,11 @@ def _random_getnode(): + + _node = None + ++_NODE_GETTERS_WIN32 = [_windll_getnode, _netbios_getnode, _ipconfig_getnode] ++ ++_NODE_GETTERS_UNIX = [_unixdll_getnode, _ifconfig_getnode, _arp_getnode, ++ _lanscan_getnode, _netstat_getnode] ++ + def getnode(): + """Get the hardware address as a 48-bit positive integer. + +@@ -537,18 +542,19 @@ def getnode(): + + import sys + if sys.platform == 'win32': +- getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode] ++ getters = _NODE_GETTERS_WIN32 + else: +- getters = [_unixdll_getnode, _ifconfig_getnode, _arp_getnode, +- _lanscan_getnode, _netstat_getnode] ++ getters = _NODE_GETTERS_UNIX + + for getter in getters + [_random_getnode]: + try: + _node = getter() + except: + continue +- if _node is not None: ++ if (_node is not None) and (0 <= _node < (1 << 48)): + return _node ++ assert False, '_random_getnode() returned invalid value: {}'.format(_node) ++ + + _last_timestamp = None + +diff --git a/Lib/webbrowser.py b/Lib/webbrowser.py +index 23891796e3..15eeb660e2 100755 +--- a/Lib/webbrowser.py ++++ b/Lib/webbrowser.py +@@ -319,11 +319,10 @@ Chromium = Chrome + class Opera(UnixBrowser): + "Launcher class for Opera browser." + +- raise_opts = ["-noraise", ""] +- remote_args = ['-remote', 'openURL(%s%action)'] ++ remote_args = ['%action', '%s'] + remote_action = "" +- remote_action_newwin = ",new-window" +- remote_action_newtab = ",new-page" ++ remote_action_newwin = "--new-window" ++ remote_action_newtab = "" + background = True + + +diff --git a/Lib/zipfile.py b/Lib/zipfile.py +index 3ab66cea69..991a0add20 100644 +--- a/Lib/zipfile.py ++++ b/Lib/zipfile.py +@@ -131,6 +131,29 @@ _CD64_NUMBER_ENTRIES_TOTAL = 7 + _CD64_DIRECTORY_SIZE = 8 + _CD64_OFFSET_START_CENTDIR = 9 + ++_DD_SIGNATURE = 0x08074b50 ++ ++_EXTRA_FIELD_STRUCT = struct.Struct(' PY_SIZE_MAX / sizeof(DBT)) { ++ PyErr_NoMemory(); ++ PyErr_Print(); ++ } ++ else { ++ dbts = (DBT *)malloc(sizeof(DBT) * listlen); ++ if (dbts == NULL) { ++ PyErr_NoMemory(); ++ PyErr_Print(); ++ } ++ else { ++ for (i = 0; i < listlen; i++) { ++ if (!PyBytes_Check(PyList_GetItem(result, i))) { ++ PyErr_SetString(PyExc_TypeError, + #if (PY_VERSION_HEX < 0x03000000) + "The list returned by DB->associate callback should be a list of strings."); + #else + "The list returned by DB->associate callback should be a list of bytes."); + #endif +- PyErr_Print(); +- } +- +- PyBytes_AsStringAndSize( +- PyList_GetItem(result, i), +- &data, &size); +- +- CLEAR_DBT(dbts[i]); +- dbts[i].data = malloc(size); /* TODO, check this */ +- +- if (dbts[i].data) +- { +- memcpy(dbts[i].data, data, size); +- dbts[i].size = size; +- dbts[i].ulen = dbts[i].size; +- dbts[i].flags = DB_DBT_APPMALLOC; /* DB will free */ +- } +- else +- { +- PyErr_SetString(PyExc_MemoryError, +- "malloc failed in _db_associateCallback (list)"); +- PyErr_Print(); ++ break; ++ } ++ ++ if (PyBytes_AsStringAndSize(PyList_GetItem(result, i), ++ &data, &size) < 0) { ++ break; ++ } ++ ++ CLEAR_DBT(dbts[i]); ++ dbts[i].data = malloc(size); ++ if (dbts[i].data) { ++ memcpy(dbts[i].data, data, size); ++ dbts[i].size = size; ++ dbts[i].ulen = dbts[i].size; ++ /* DB will free. */ ++ dbts[i].flags = DB_DBT_APPMALLOC; ++ } ++ else { ++ PyErr_SetString(PyExc_MemoryError, ++ "malloc failed in " ++ "_db_associateCallback (list)"); ++ break; ++ } ++ } ++ if (PyErr_Occurred()) { ++ PyErr_Print(); ++ while (i--) { ++ free(dbts[i].data); ++ } ++ free(dbts); ++ } ++ else { ++ CLEAR_DBT(*secKey); ++ ++ secKey->data = dbts; ++ secKey->size = listlen; ++ secKey->flags = DB_DBT_APPMALLOC | DB_DBT_MULTIPLE; ++ retval = 0; ++ } + } + } +- +- CLEAR_DBT(*secKey); +- +- secKey->data = dbts; +- secKey->size = listlen; +- secKey->flags = DB_DBT_APPMALLOC | DB_DBT_MULTIPLE; +- retval = 0; + } + #endif + else { +@@ -2242,7 +2257,7 @@ static PyObject* + DB_join(DBObject* self, PyObject* args) + { + int err, flags=0; +- int length, x; ++ Py_ssize_t length, x; + PyObject* cursorsObj; + DBC** cursors; + DBC* dbc; +@@ -2259,6 +2274,12 @@ DB_join(DBObject* self, PyObject* args) + } + + length = PyObject_Length(cursorsObj); ++ if (length == -1) { ++ return NULL; ++ } ++ if (length >= PY_SSIZE_T_MAX / sizeof(DBC*)) { ++ return PyErr_NoMemory(); ++ } + cursors = malloc((length+1) * sizeof(DBC*)); + if (!cursors) { + PyErr_NoMemory(); +@@ -2276,6 +2297,7 @@ DB_join(DBObject* self, PyObject* args) + PyErr_SetString(PyExc_TypeError, + "Sequence of DBCursor objects expected"); + free(cursors); ++ Py_DECREF(item); + return NULL; + } + cursors[x] = ((DBCursorObject*)item)->dbc; +diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c +index 2e4da4c211..3ca393082f 100644 +--- a/Modules/_collectionsmodule.c ++++ b/Modules/_collectionsmodule.c +@@ -639,7 +639,7 @@ deque_remove(dequeobject *deque, PyObject *value) + PyDoc_STRVAR(remove_doc, + "D.remove(value) -- remove first occurrence of value."); + +-static void ++static int + deque_clear(dequeobject *deque) + { + block *b; +@@ -650,7 +650,7 @@ deque_clear(dequeobject *deque) + PyObject *item; + + if (deque->len == 0) +- return; ++ return 0; + + /* During the process of clearing a deque, decrefs can cause the + deque to mutate. To avoid fatal confusion, we have to make the +@@ -701,7 +701,7 @@ deque_clear(dequeobject *deque) + } + assert(leftblock->rightlink == NULL); + freeblock(leftblock); +- return; ++ return 0; + + alternate_method: + while (deque->len) { +@@ -709,6 +709,7 @@ deque_clear(dequeobject *deque) + assert (item != NULL); + Py_DECREF(item); + } ++ return 0; + } + + static PyObject * +@@ -858,11 +859,20 @@ deque_traverse(dequeobject *deque, visitproc visit, void *arg) + static PyObject * + deque_copy(PyObject *deque) + { ++ PyObject *result; + if (((dequeobject *)deque)->maxlen == -1) +- return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL); ++ result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL); + else +- return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi", ++ result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi", + deque, ((dequeobject *)deque)->maxlen, NULL); ++ if (result != NULL && !PyObject_TypeCheck(result, &deque_type)) { ++ PyErr_Format(PyExc_TypeError, ++ "%.200s() must return a deque, not %.200s", ++ Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name); ++ Py_DECREF(result); ++ return NULL; ++ } ++ return result; + } + + PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque."); +diff --git a/Modules/_csv.c b/Modules/_csv.c +index c39c0f10c3..88e3e90658 100644 +--- a/Modules/_csv.c ++++ b/Modules/_csv.c +@@ -224,7 +224,7 @@ _set_int(const char *name, int *target, PyObject *src, int dflt) + if (src == NULL) + *target = dflt; + else { +- if (!PyInt_Check(src) && !PyLong_Check(src)) { ++ if (!_PyAnyInt_Check(src)) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be an integer", name); + return -1; +@@ -565,24 +565,23 @@ parse_save_field(ReaderObj *self) + static int + parse_grow_buff(ReaderObj *self) + { +- if (self->field_size == 0) { +- self->field_size = 4096; +- if (self->field != NULL) +- PyMem_Free(self->field); +- self->field = PyMem_Malloc(self->field_size); +- } +- else { +- if (self->field_size > INT_MAX / 2) { +- PyErr_NoMemory(); +- return 0; +- } +- self->field_size *= 2; +- self->field = PyMem_Realloc(self->field, self->field_size); ++ unsigned field_size_new; ++ char *field_new; ++ ++ assert((unsigned)self->field_size <= INT_MAX); ++ ++ field_size_new = self->field_size ? 2 * (unsigned)self->field_size : 4096; ++ if (field_size_new > INT_MAX) { ++ PyErr_NoMemory(); ++ return 0; + } +- if (self->field == NULL) { ++ field_new = (char *)PyMem_Realloc(self->field, field_size_new); ++ if (field_new == NULL) { + PyErr_NoMemory(); + return 0; + } ++ self->field = field_new; ++ self->field_size = (int)field_size_new; + return 1; + } + +@@ -1088,31 +1087,24 @@ join_append_data(WriterObj *self, char *field, int quote_empty, + static int + join_check_rec_size(WriterObj *self, int rec_len) + { ++ unsigned rec_size_new; ++ char *rec_new; + +- if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) { +- PyErr_NoMemory(); +- return 0; +- } ++ assert(rec_len >= 0); + + if (rec_len > self->rec_size) { +- if (self->rec_size == 0) { +- self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR; +- if (self->rec != NULL) +- PyMem_Free(self->rec); +- self->rec = PyMem_Malloc(self->rec_size); +- } +- else { +- char *old_rec = self->rec; +- +- self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR; +- self->rec = PyMem_Realloc(self->rec, self->rec_size); +- if (self->rec == NULL) +- PyMem_Free(old_rec); ++ rec_size_new = (unsigned)(rec_len / MEM_INCR + 1) * MEM_INCR; ++ if (rec_size_new > INT_MAX) { ++ PyErr_NoMemory(); ++ return 0; + } +- if (self->rec == NULL) { ++ rec_new = (char *)PyMem_Realloc(self->rec, rec_size_new); ++ if (rec_new == NULL) { + PyErr_NoMemory(); + return 0; + } ++ self->rec = rec_new; ++ self->rec_size = (int)rec_size_new; + } + return 1; + } +@@ -1452,7 +1444,7 @@ csv_field_size_limit(PyObject *module, PyObject *args) + if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit)) + return NULL; + if (new_limit != NULL) { +- if (!PyInt_Check(new_limit) && !PyLong_Check(new_limit)) { ++ if (!_PyAnyInt_Check(new_limit)) { + PyErr_Format(PyExc_TypeError, + "limit must be an integer"); + return NULL; +diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c +index 25740ed771..fabbdf13e9 100644 +--- a/Modules/_ctypes/_ctypes.c ++++ b/Modules/_ctypes/_ctypes.c +@@ -547,7 +547,7 @@ static PyObject * + CDataType_from_address(PyObject *type, PyObject *value) + { + void *buf; +- if (!PyInt_Check(value) && !PyLong_Check(value)) { ++ if (!_PyAnyInt_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "integer expected"); + return NULL; +@@ -691,7 +691,7 @@ CDataType_in_dll(PyObject *type, PyObject *args) + obj = PyObject_GetAttrString(dll, "_handle"); + if (!obj) + return NULL; +- if (!PyInt_Check(obj) && !PyLong_Check(obj)) { ++ if (!_PyAnyInt_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(obj); +@@ -1779,7 +1779,7 @@ c_void_p_from_param(PyObject *type, PyObject *value) + } + /* Should probably allow buffer interface as well */ + /* int, long */ +- if (PyInt_Check(value) || PyLong_Check(value)) { ++ if (_PyAnyInt_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("P"); + +@@ -3419,7 +3419,7 @@ static int + _get_name(PyObject *obj, char **pname) + { + #ifdef MS_WIN32 +- if (PyInt_Check(obj) || PyLong_Check(obj)) { ++ if (_PyAnyInt_Check(obj)) { + /* We have to use MAKEINTRESOURCEA for Windows CE. + Works on Windows as well, of course. + */ +@@ -3469,7 +3469,7 @@ PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds) + Py_DECREF(ftuple); + return NULL; + } +- if (!PyInt_Check(obj) && !PyLong_Check(obj)) { ++ if (!_PyAnyInt_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(ftuple); +@@ -3600,8 +3600,7 @@ PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + #endif + + if (1 == PyTuple_GET_SIZE(args) +- && (PyInt_Check(PyTuple_GET_ITEM(args, 0)) +- || PyLong_Check(PyTuple_GET_ITEM(args, 0)))) { ++ && _PyAnyInt_Check(PyTuple_GET_ITEM(args, 0))) { + CDataObject *ob; + void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0)); + if (ptr == NULL && PyErr_Occurred()) +diff --git a/Modules/_ctypes/_ctypes_test.c b/Modules/_ctypes/_ctypes_test.c +index f295c6fc4c..93876d3d01 100644 +--- a/Modules/_ctypes/_ctypes_test.c ++++ b/Modules/_ctypes/_ctypes_test.c +@@ -52,6 +52,19 @@ _testfunc_cbk_large_struct(Test in, void (*func)(Test)) + func(in); + } + ++/* ++ * See issue 29565. Update a structure passed by value; ++ * the caller should not see any change. ++ */ ++ ++EXPORT(void) ++_testfunc_large_struct_update_value(Test in) ++{ ++ in.first = 0x0badf00d; ++ in.second = 0x0badf00d; ++ in.third = 0x0badf00d; ++} ++ + EXPORT(void)testfunc_array(int values[4]) + { + printf("testfunc_array %d %d %d %d\n", +@@ -642,6 +655,200 @@ EXPORT(void) TwoOutArgs(int a, int *pi, int b, int *pj) + *pj += b; + } + ++#ifdef MS_WIN32 ++ ++typedef struct { ++ char f1; ++} Size1; ++ ++typedef struct { ++ char f1; ++ char f2; ++} Size2; ++ ++typedef struct { ++ char f1; ++ char f2; ++ char f3; ++} Size3; ++ ++typedef struct { ++ char f1; ++ char f2; ++ char f3; ++ char f4; ++} Size4; ++ ++typedef struct { ++ char f1; ++ char f2; ++ char f3; ++ char f4; ++ char f5; ++} Size5; ++ ++typedef struct { ++ char f1; ++ char f2; ++ char f3; ++ char f4; ++ char f5; ++ char f6; ++} Size6; ++ ++typedef struct { ++ char f1; ++ char f2; ++ char f3; ++ char f4; ++ char f5; ++ char f6; ++ char f7; ++} Size7; ++ ++typedef struct { ++ char f1; ++ char f2; ++ char f3; ++ char f4; ++ char f5; ++ char f6; ++ char f7; ++ char f8; ++} Size8; ++ ++typedef struct { ++ char f1; ++ char f2; ++ char f3; ++ char f4; ++ char f5; ++ char f6; ++ char f7; ++ char f8; ++ char f9; ++} Size9; ++ ++typedef struct { ++ char f1; ++ char f2; ++ char f3; ++ char f4; ++ char f5; ++ char f6; ++ char f7; ++ char f8; ++ char f9; ++ char f10; ++} Size10; ++ ++EXPORT(Size1) TestSize1() { ++ Size1 f; ++ f.f1 = 'a'; ++ return f; ++} ++ ++EXPORT(Size2) TestSize2() { ++ Size2 f; ++ f.f1 = 'a'; ++ f.f2 = 'b'; ++ return f; ++} ++ ++EXPORT(Size3) TestSize3() { ++ Size3 f; ++ f.f1 = 'a'; ++ f.f2 = 'b'; ++ f.f3 = 'c'; ++ return f; ++} ++ ++EXPORT(Size4) TestSize4() { ++ Size4 f; ++ f.f1 = 'a'; ++ f.f2 = 'b'; ++ f.f3 = 'c'; ++ f.f4 = 'd'; ++ return f; ++} ++ ++EXPORT(Size5) TestSize5() { ++ Size5 f; ++ f.f1 = 'a'; ++ f.f2 = 'b'; ++ f.f3 = 'c'; ++ f.f4 = 'd'; ++ f.f5 = 'e'; ++ return f; ++} ++ ++EXPORT(Size6) TestSize6() { ++ Size6 f; ++ f.f1 = 'a'; ++ f.f2 = 'b'; ++ f.f3 = 'c'; ++ f.f4 = 'd'; ++ f.f5 = 'e'; ++ f.f6 = 'f'; ++ return f; ++} ++ ++EXPORT(Size7) TestSize7() { ++ Size7 f; ++ f.f1 = 'a'; ++ f.f2 = 'b'; ++ f.f3 = 'c'; ++ f.f4 = 'd'; ++ f.f5 = 'e'; ++ f.f6 = 'f'; ++ f.f7 = 'g'; ++ return f; ++} ++ ++EXPORT(Size8) TestSize8() { ++ Size8 f; ++ f.f1 = 'a'; ++ f.f2 = 'b'; ++ f.f3 = 'c'; ++ f.f4 = 'd'; ++ f.f5 = 'e'; ++ f.f6 = 'f'; ++ f.f7 = 'g'; ++ f.f8 = 'h'; ++ return f; ++} ++ ++EXPORT(Size9) TestSize9() { ++ Size9 f; ++ f.f1 = 'a'; ++ f.f2 = 'b'; ++ f.f3 = 'c'; ++ f.f4 = 'd'; ++ f.f5 = 'e'; ++ f.f6 = 'f'; ++ f.f7 = 'g'; ++ f.f8 = 'h'; ++ f.f9 = 'i'; ++ return f; ++} ++ ++EXPORT(Size10) TestSize10() { ++ Size10 f; ++ f.f1 = 'a'; ++ f.f2 = 'b'; ++ f.f3 = 'c'; ++ f.f4 = 'd'; ++ f.f5 = 'e'; ++ f.f6 = 'f'; ++ f.f7 = 'g'; ++ f.f8 = 'h'; ++ f.f9 = 'i'; ++ f.f10 = 'j'; ++ return f; ++} ++ ++#endif ++ + #ifdef MS_WIN32 + EXPORT(S2H) __stdcall s_ret_2h_func(S2H inp) { return ret_2h_func(inp); } + EXPORT(S8I) __stdcall s_ret_8i_func(S8I inp) { return ret_8i_func(inp); } +diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c +index 91233d508c..63f3c21784 100644 +--- a/Modules/_ctypes/callproc.c ++++ b/Modules/_ctypes/callproc.c +@@ -747,9 +747,9 @@ ffi_type *_ctypes_get_ffi_type(PyObject *obj) + It returns small structures in registers + */ + if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) { +- if (dict->ffi_type_pointer.size <= 4) ++ if (can_return_struct_as_int(dict->ffi_type_pointer.size)) + return &ffi_type_sint32; +- else if (dict->ffi_type_pointer.size <= 8) ++ else if (can_return_struct_as_sint64 (dict->ffi_type_pointer.size)) + return &ffi_type_sint64; + } + #endif +diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c +index 6f632d0a07..46f041b00e 100644 +--- a/Modules/_ctypes/cfield.c ++++ b/Modules/_ctypes/cfield.c +@@ -1361,7 +1361,7 @@ z_set(void *ptr, PyObject *value, Py_ssize_t size) + return NULL; + *(char **)ptr = PyString_AS_STRING(str); + return str; +- } else if (PyInt_Check(value) || PyLong_Check(value)) { ++ } else if (_PyAnyInt_Check(value)) { + #if SIZEOF_VOID_P == SIZEOF_LONG_LONG + *(char **)ptr = (char *)PyInt_AsUnsignedLongLongMask(value); + #else +@@ -1410,7 +1410,7 @@ Z_set(void *ptr, PyObject *value, Py_ssize_t size) + _ctypes_conversion_errors); + if (!value) + return NULL; +- } else if (PyInt_Check(value) || PyLong_Check(value)) { ++ } else if (_PyAnyInt_Check(value)) { + #if SIZEOF_VOID_P == SIZEOF_LONG_LONG + *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value); + #else +@@ -1565,7 +1565,7 @@ P_set(void *ptr, PyObject *value, Py_ssize_t size) + _RET(value); + } + +- if (!PyInt_Check(value) && !PyLong_Check(value)) { ++ if (!_PyAnyInt_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "cannot be converted to pointer"); + return NULL; +diff --git a/Modules/_ctypes/libffi_msvc/ffi.c b/Modules/_ctypes/libffi_msvc/ffi.c +index 515d802fd8..15a100fe34 100644 +--- a/Modules/_ctypes/libffi_msvc/ffi.c ++++ b/Modules/_ctypes/libffi_msvc/ffi.c +@@ -119,13 +119,28 @@ void ffi_prep_args(char *stack, extended_cif *ecif) + argp += z; + } + +- if (argp - stack > ecif->cif->bytes) ++ if (argp >= stack && (unsigned)(argp - stack) > ecif->cif->bytes) + { + Py_FatalError("FFI BUG: not enough stack space for arguments"); + } + return; + } + ++/* ++Per: https://msdn.microsoft.com/en-us/library/7572ztz4.aspx ++To be returned by value in RAX, user-defined types must have a length ++of 1, 2, 4, 8, 16, 32, or 64 bits ++*/ ++int can_return_struct_as_int(size_t s) ++{ ++ return s == 1 || s == 2 || s == 4; ++} ++ ++int can_return_struct_as_sint64(size_t s) ++{ ++ return s == 8; ++} ++ + /* Perform machine dependent cif processing */ + ffi_status ffi_prep_cif_machdep(ffi_cif *cif) + { +@@ -144,9 +159,9 @@ ffi_status ffi_prep_cif_machdep(ffi_cif *cif) + /* MSVC returns small structures in registers. Put in cif->flags + the value FFI_TYPE_STRUCT only if the structure is big enough; + otherwise, put the 4- or 8-bytes integer type. */ +- if (cif->rtype->size <= 4) ++ if (can_return_struct_as_int(cif->rtype->size)) + cif->flags = FFI_TYPE_INT; +- else if (cif->rtype->size <= 8) ++ else if (can_return_struct_as_sint64(cif->rtype->size)) + cif->flags = FFI_TYPE_SINT64; + else + cif->flags = FFI_TYPE_STRUCT; +@@ -220,6 +235,20 @@ ffi_call(/*@dependent@*/ ffi_cif *cif, + break; + #else + case FFI_SYSV: ++ /* use a local scope for the 'i' variable */ ++ { ++ unsigned i; ++ /* If a single argument takes more than 8 bytes, ++ then a copy is passed by reference. */ ++ for (i = 0; i < cif->nargs; i++) { ++ size_t z = cif->arg_types[i]->size; ++ if (z > 8) { ++ void *temp = alloca(z); ++ memcpy(temp, avalue[i], z); ++ avalue[i] = temp; ++ } ++ } ++ } + /*@-usedef@*/ + return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes, + cif->flags, ecif.rvalue, fn); +diff --git a/Modules/_ctypes/libffi_msvc/ffi.h b/Modules/_ctypes/libffi_msvc/ffi.h +index efb14c5f6f..ba74202720 100644 +--- a/Modules/_ctypes/libffi_msvc/ffi.h ++++ b/Modules/_ctypes/libffi_msvc/ffi.h +@@ -136,6 +136,9 @@ typedef struct _ffi_type + /*@null@*/ struct _ffi_type **elements; + } ffi_type; + ++int can_return_struct_as_int(size_t); ++int can_return_struct_as_sint64(size_t); ++ + /* These are defined in types.c */ + extern ffi_type ffi_type_void; + extern ffi_type ffi_type_uint8; +diff --git a/Modules/_ctypes/libffi_msvc/prep_cif.c b/Modules/_ctypes/libffi_msvc/prep_cif.c +index b28f895a1e..80c5a60818 100644 +--- a/Modules/_ctypes/libffi_msvc/prep_cif.c ++++ b/Modules/_ctypes/libffi_msvc/prep_cif.c +@@ -117,7 +117,8 @@ ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, + /* Make space for the return structure pointer */ + if (cif->rtype->type == FFI_TYPE_STRUCT + #ifdef _WIN32 +- && (cif->rtype->size > 8) /* MSVC returns small structs in registers */ ++ && !can_return_struct_as_int(cif->rtype->size) /* MSVC returns small structs in registers */ ++ && !can_return_struct_as_sint64(cif->rtype->size) + #endif + #ifdef SPARC + && (cif->abi != FFI_V9 || cif->rtype->size > 32) +@@ -146,7 +147,9 @@ ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, + bytes += sizeof(void*); + else + #elif defined (_WIN64) +- if ((*ptr)->type == FFI_TYPE_STRUCT && ((*ptr)->size > 8)) ++ if ((*ptr)->type == FFI_TYPE_STRUCT && ++ !can_return_struct_as_int((*ptr)->size) && ++ !can_return_struct_as_sint64((*ptr)->size)) + bytes += sizeof(void*); + else + #endif +diff --git a/Modules/_cursesmodule.c b/Modules/_cursesmodule.c +index 935712a0be..0ec4ee1244 100644 +--- a/Modules/_cursesmodule.c ++++ b/Modules/_cursesmodule.c +@@ -194,7 +194,7 @@ PyCursesCheckERR(int code, char *fname) + static int + PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) + { +- if (PyInt_Check(obj) || PyLong_Check(obj)) { ++ if (_PyAnyInt_Check(obj)) { + *ch = (chtype) PyInt_AsLong(obj); + if (*ch == (chtype) -1 && PyErr_Occurred()) + return 0; +@@ -2603,7 +2603,7 @@ PyCurses_UnCtrl(PyObject *self, PyObject *args) + + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + +- if (PyInt_Check(temp) || PyLong_Check(temp)) { ++ if (_PyAnyInt_Check(temp)) { + ch = (chtype) PyInt_AsLong(temp); + if (ch == (chtype) -1 && PyErr_Occurred()) + return NULL; +@@ -2628,7 +2628,7 @@ PyCurses_UngetCh(PyObject *self, PyObject *args) + + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + +- if (PyInt_Check(temp) || PyLong_Check(temp)) { ++ if (_PyAnyInt_Check(temp)) { + ch = (int) PyInt_AsLong(temp); + if (ch == -1 && PyErr_Occurred()) + return NULL; +diff --git a/Modules/_elementtree.c b/Modules/_elementtree.c +index 1d316a1c91..b38e0ab329 100644 +--- a/Modules/_elementtree.c ++++ b/Modules/_elementtree.c +@@ -1347,7 +1347,7 @@ element_subscr(PyObject* self_, PyObject* item) + ElementObject* self = (ElementObject*) self_; + + #if (PY_VERSION_HEX < 0x02050000) +- if (PyInt_Check(item) || PyLong_Check(item)) { ++ if (_PyAnyInt_Check(item)) { + long i = PyInt_AsLong(item); + #else + if (PyIndex_Check(item)) { +@@ -1404,7 +1404,7 @@ element_ass_subscr(PyObject* self_, PyObject* item, PyObject* value) + ElementObject* self = (ElementObject*) self_; + + #if (PY_VERSION_HEX < 0x02050000) +- if (PyInt_Check(item) || PyLong_Check(item)) { ++ if (_PyAnyInt_Check(item)) { + long i = PyInt_AsLong(item); + #else + if (PyIndex_Check(item)) { +@@ -2574,6 +2574,11 @@ xmlparser(PyObject* self_, PyObject* args, PyObject* kw) + PyErr_NoMemory(); + return NULL; + } ++ /* expat < 2.1.0 has no XML_SetHashSalt() */ ++ if (EXPAT(SetHashSalt) != NULL) { ++ EXPAT(SetHashSalt)(self->parser, ++ (unsigned long)_Py_HashSecret.prefix); ++ } + + ALLOC(sizeof(XMLParserObject), "create expatparser"); + +diff --git a/Modules/_io/iobase.c b/Modules/_io/iobase.c +index d813daf6cf..17b905ad8f 100644 +--- a/Modules/_io/iobase.c ++++ b/Modules/_io/iobase.c +@@ -177,17 +177,25 @@ _PyIOBase_check_closed(PyObject *self, PyObject *args) + static PyObject * + iobase_close(PyObject *self, PyObject *args) + { +- PyObject *res; ++ PyObject *res, *exc, *val, *tb; ++ int rc; + + if (IS_CLOSED(self)) + Py_RETURN_NONE; + + res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL); +- PyObject_SetAttrString(self, "__IOBase_closed", Py_True); ++ ++ PyErr_Fetch(&exc, &val, &tb); ++ rc = PyObject_SetAttrString(self, "__IOBase_closed", Py_True); ++ _PyErr_ReplaceException(exc, val, tb); ++ if (rc < 0) { ++ Py_CLEAR(res); ++ } ++ + if (res == NULL) { + return NULL; + } +- Py_XDECREF(res); ++ Py_DECREF(res); + Py_RETURN_NONE; + } + +diff --git a/Modules/_io/textio.c b/Modules/_io/textio.c +index bf37f72bd1..1979539cc0 100644 +--- a/Modules/_io/textio.c ++++ b/Modules/_io/textio.c +@@ -707,6 +707,8 @@ typedef struct + PyObject *dict; + } textio; + ++static void ++textiowrapper_set_decoded_chars(textio *self, PyObject *chars); + + /* A couple of specialized cases in order to bypass the slow incremental + encoding methods for the most popular encodings. */ +@@ -1329,6 +1331,7 @@ textiowrapper_write(textio *self, PyObject *args) + Py_DECREF(ret); + } + ++ textiowrapper_set_decoded_chars(self, NULL); + Py_CLEAR(self->snapshot); + + if (self->decoder) { +@@ -1534,6 +1537,7 @@ textiowrapper_read(textio *self, PyObject *args) + if (final == NULL) + goto fail; + ++ textiowrapper_set_decoded_chars(self, NULL); + Py_CLEAR(self->snapshot); + return final; + } +diff --git a/Modules/_json.c b/Modules/_json.c +index 39ec467b09..3a88882f0c 100644 +--- a/Modules/_json.c ++++ b/Modules/_json.c +@@ -1893,7 +1893,7 @@ _encoded_const(PyObject *obj) + if (s_null == NULL) { + s_null = PyString_InternFromString("null"); + } +- Py_INCREF(s_null); ++ Py_XINCREF(s_null); + return s_null; + } + else if (obj == Py_True) { +@@ -1901,7 +1901,7 @@ _encoded_const(PyObject *obj) + if (s_true == NULL) { + s_true = PyString_InternFromString("true"); + } +- Py_INCREF(s_true); ++ Py_XINCREF(s_true); + return s_true; + } + else if (obj == Py_False) { +@@ -1909,7 +1909,7 @@ _encoded_const(PyObject *obj) + if (s_false == NULL) { + s_false = PyString_InternFromString("false"); + } +- Py_INCREF(s_false); ++ Py_XINCREF(s_false); + return s_false; + } + else { +@@ -1981,7 +1981,7 @@ encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssi + return -1; + return _steal_list_append(rval, encoded); + } +- else if (PyInt_Check(obj) || PyLong_Check(obj)) { ++ else if (_PyAnyInt_Check(obj)) { + PyObject *encoded = PyObject_Str(obj); + if (encoded == NULL) + return -1; +@@ -2131,7 +2131,7 @@ encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ss + if (kstr == NULL) + goto bail; + } +- else if (PyInt_Check(key) || PyLong_Check(key)) { ++ else if (_PyAnyInt_Check(key)) { + kstr = PyObject_Str(key); + if (kstr == NULL) + goto bail; +diff --git a/Modules/_lsprof.c b/Modules/_lsprof.c +index 6090c7dd23..945354fcfa 100644 +--- a/Modules/_lsprof.c ++++ b/Modules/_lsprof.c +@@ -807,11 +807,11 @@ static PyMethodDef profiler_methods[] = { + }; + + PyDoc_STRVAR(profiler_doc, "\ +-Profiler(custom_timer=None, time_unit=None, subcalls=True, builtins=True)\n\ ++Profiler(timer=None, timeunit=None, subcalls=True, builtins=True)\n\ + \n\ + Builds a profiler object using the specified timer function.\n\ + The default timer is a fast built-in one based on real time.\n\ +- For custom timer functions returning integers, time_unit can\n\ ++ For custom timer functions returning integers, timeunit can\n\ + be a float specifying a scale (i.e. how long each integer unit\n\ + is, in seconds).\n\ + "); +diff --git a/Modules/_randommodule.c b/Modules/_randommodule.c +index 2e49db6ef7..2c0daef71f 100644 +--- a/Modules/_randommodule.c ++++ b/Modules/_randommodule.c +@@ -415,7 +415,7 @@ random_jumpahead(RandomObject *self, PyObject *n) + PyObject *remobj; + unsigned long *mt, tmp, nonzero; + +- if (!PyInt_Check(n) && !PyLong_Check(n)) { ++ if (!_PyAnyInt_Check(n)) { + PyErr_Format(PyExc_TypeError, "jumpahead requires an " + "integer, not '%s'", + Py_TYPE(n)->tp_name); +diff --git a/Modules/_sqlite/connection.c b/Modules/_sqlite/connection.c +index 0603b4307b..c3f39fd78a 100644 +--- a/Modules/_sqlite/connection.c ++++ b/Modules/_sqlite/connection.c +@@ -675,7 +675,7 @@ void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** + Py_DECREF(py_retval); + } + if (!ok) { +- if (_enable_callback_tracebacks) { ++ if (_pysqlite_enable_callback_tracebacks) { + PyErr_Print(); + } else { + PyErr_Clear(); +@@ -711,7 +711,7 @@ static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_ + + if (PyErr_Occurred()) { + *aggregate_instance = 0; +- if (_enable_callback_tracebacks) { ++ if (_pysqlite_enable_callback_tracebacks) { + PyErr_Print(); + } else { + PyErr_Clear(); +@@ -735,7 +735,7 @@ static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_ + Py_DECREF(args); + + if (!function_result) { +- if (_enable_callback_tracebacks) { ++ if (_pysqlite_enable_callback_tracebacks) { + PyErr_Print(); + } else { + PyErr_Clear(); +@@ -781,7 +781,7 @@ void _pysqlite_final_callback(sqlite3_context* context) + Py_DECREF(function_result); + } + if (!ok) { +- if (_enable_callback_tracebacks) { ++ if (_pysqlite_enable_callback_tracebacks) { + PyErr_Print(); + } else { + PyErr_Clear(); +@@ -936,7 +936,7 @@ static int _authorizer_callback(void* user_arg, int action, const char* arg1, co + ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source); + + if (!ret) { +- if (_enable_callback_tracebacks) { ++ if (_pysqlite_enable_callback_tracebacks) { + PyErr_Print(); + } else { + PyErr_Clear(); +@@ -972,7 +972,7 @@ static int _progress_handler(void* user_arg) + ret = PyObject_CallFunction((PyObject*)user_arg, ""); + + if (!ret) { +- if (_enable_callback_tracebacks) { ++ if (_pysqlite_enable_callback_tracebacks) { + PyErr_Print(); + } else { + PyErr_Clear(); +diff --git a/Modules/_sqlite/cursor.c b/Modules/_sqlite/cursor.c +index b7c2d798da..e5cd721a5e 100644 +--- a/Modules/_sqlite/cursor.c ++++ b/Modules/_sqlite/cursor.c +@@ -147,7 +147,7 @@ PyObject* _pysqlite_get_converter(PyObject* key) + return NULL; + } + +- retval = PyDict_GetItem(converters, upcase_key); ++ retval = PyDict_GetItem(_pysqlite_converters, upcase_key); + Py_DECREF(upcase_key); + + return retval; +@@ -655,7 +655,7 @@ PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* + } else { + if (PyErr_Occurred()) { + /* there was an error that occurred in a user-defined callback */ +- if (_enable_callback_tracebacks) { ++ if (_pysqlite_enable_callback_tracebacks) { + PyErr_Print(); + } else { + PyErr_Clear(); +diff --git a/Modules/_sqlite/module.c b/Modules/_sqlite/module.c +index 33611d9dad..fa45edfff9 100644 +--- a/Modules/_sqlite/module.c ++++ b/Modules/_sqlite/module.c +@@ -39,8 +39,8 @@ PyObject* pysqlite_Error, *pysqlite_Warning, *pysqlite_InterfaceError, *pysqlite + *pysqlite_InternalError, *pysqlite_OperationalError, *pysqlite_ProgrammingError, + *pysqlite_IntegrityError, *pysqlite_DataError, *pysqlite_NotSupportedError, *pysqlite_OptimizedUnicode; + +-PyObject* converters; +-int _enable_callback_tracebacks; ++PyObject* _pysqlite_converters; ++int _pysqlite_enable_callback_tracebacks; + int pysqlite_BaseTypeAdapted; + + static PyObject* module_connect(PyObject* self, PyObject* args, PyObject* +@@ -190,7 +190,7 @@ static PyObject* module_register_converter(PyObject* self, PyObject* args) + goto error; + } + +- if (PyDict_SetItem(converters, name, callable) != 0) { ++ if (PyDict_SetItem(_pysqlite_converters, name, callable) != 0) { + goto error; + } + +@@ -208,7 +208,7 @@ Registers a converter with pysqlite. Non-standard."); + + static PyObject* enable_callback_tracebacks(PyObject* self, PyObject* args) + { +- if (!PyArg_ParseTuple(args, "i", &_enable_callback_tracebacks)) { ++ if (!PyArg_ParseTuple(args, "i", &_pysqlite_enable_callback_tracebacks)) { + return NULL; + } + +@@ -223,12 +223,12 @@ Enable or disable callback functions throwing errors to stderr."); + + static void converters_init(PyObject* dict) + { +- converters = PyDict_New(); +- if (!converters) { ++ _pysqlite_converters = PyDict_New(); ++ if (!_pysqlite_converters) { + return; + } + +- PyDict_SetItemString(dict, "converters", converters); ++ PyDict_SetItemString(dict, "converters", _pysqlite_converters); + } + + static PyMethodDef module_methods[] = { +@@ -428,7 +428,7 @@ PyMODINIT_FUNC init_sqlite3(void) + /* initialize the default converters */ + converters_init(dict); + +- _enable_callback_tracebacks = 0; ++ _pysqlite_enable_callback_tracebacks = 0; + + pysqlite_BaseTypeAdapted = 0; + +diff --git a/Modules/_sqlite/module.h b/Modules/_sqlite/module.h +index 8d17d6173f..322452fdd9 100644 +--- a/Modules/_sqlite/module.h ++++ b/Modules/_sqlite/module.h +@@ -40,17 +40,13 @@ extern PyObject* pysqlite_NotSupportedError; + + extern PyObject* pysqlite_OptimizedUnicode; + +-/* the functions time.time() and time.sleep() */ +-extern PyObject* time_time; +-extern PyObject* time_sleep; +- + /* A dictionary, mapping colum types (INTEGER, VARCHAR, etc.) to converter + * functions, that convert the SQL value to the appropriate Python value. + * The key is uppercase. + */ +-extern PyObject* converters; ++extern PyObject* _pysqlite_converters; + +-extern int _enable_callback_tracebacks; ++extern int _pysqlite_enable_callback_tracebacks; + extern int pysqlite_BaseTypeAdapted; + + #define PARSE_DECLTYPES 1 +diff --git a/Modules/_sqlite/statement.c b/Modules/_sqlite/statement.c +index 5d6263c8e6..ec60095ab8 100644 +--- a/Modules/_sqlite/statement.c ++++ b/Modules/_sqlite/statement.c +@@ -205,7 +205,7 @@ static int _need_adapt(PyObject* obj) + return 1; + } + +- if (PyInt_CheckExact(obj) || PyLong_CheckExact(obj) ++ if (_PyAnyInt_CheckExact(obj) + || PyFloat_CheckExact(obj) || PyString_CheckExact(obj) + || PyUnicode_CheckExact(obj) || PyBuffer_Check(obj)) { + return 0; +diff --git a/Modules/_sqlite/util.c b/Modules/_sqlite/util.c +index a24dd8c634..73772250f9 100644 +--- a/Modules/_sqlite/util.c ++++ b/Modules/_sqlite/util.c +@@ -132,7 +132,7 @@ _pysqlite_long_from_int64(sqlite_int64 value) + } + # endif + #endif +- return PyInt_FromLong(value); ++ return PyInt_FromLong(Py_SAFE_DOWNCAST(value, sqlite_int64, long)); + } + + sqlite_int64 +diff --git a/Modules/_sre.c b/Modules/_sre.c +index 94b3d5089c..081a1aa005 100644 +--- a/Modules/_sre.c ++++ b/Modules/_sre.c +@@ -835,7 +835,7 @@ entrance: + 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]) { ++ if (ctx->pattern[3] && (Py_uintptr_t)(end - ctx->ptr) < ctx->pattern[3]) { + TRACE(("reject (got %" PY_FORMAT_SIZE_T "d chars, " + "need %" PY_FORMAT_SIZE_T "d)\n", + (end - ctx->ptr), (Py_ssize_t) ctx->pattern[3])); +@@ -2882,7 +2882,7 @@ _compile(PyObject* self_, PyObject* args) + skip = *code; \ + VTRACE(("%lu (skip to %p)\n", \ + (unsigned long)skip, code+skip)); \ +- if (skip-adj > end-code) \ ++ if (skip-adj > (Py_uintptr_t)(end - code)) \ + FAIL; \ + code++; \ + } while (0) +@@ -2915,7 +2915,7 @@ _validate_charset(SRE_CODE *code, SRE_CODE *end) + + case SRE_OP_CHARSET: + offset = 32/sizeof(SRE_CODE); /* 32-byte bitmap */ +- if (offset > end-code) ++ if (offset > (Py_uintptr_t)(end - code)) + FAIL; + code += offset; + break; +@@ -2923,7 +2923,7 @@ _validate_charset(SRE_CODE *code, SRE_CODE *end) + case SRE_OP_BIGCHARSET: + GET_ARG; /* Number of blocks */ + offset = 256/sizeof(SRE_CODE); /* 256-byte table */ +- if (offset > end-code) ++ if (offset > (Py_uintptr_t)(end - code)) + FAIL; + /* Make sure that each byte points to a valid block */ + for (i = 0; i < 256; i++) { +@@ -2932,7 +2932,7 @@ _validate_charset(SRE_CODE *code, SRE_CODE *end) + } + code += offset; + offset = arg * 32/sizeof(SRE_CODE); /* 32-byte bitmap times arg */ +- if (offset > end-code) ++ if (offset > (Py_uintptr_t)(end - code)) + FAIL; + code += offset; + break; +@@ -2995,7 +2995,7 @@ _validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups) + 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) { ++ if (arg > 2 * (size_t)groups + 1) { + VTRACE(("arg=%d, groups=%d\n", (int)arg, (int)groups)); + FAIL; + } +@@ -3083,11 +3083,11 @@ _validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups) + GET_ARG; prefix_len = arg; + GET_ARG; /* prefix skip */ + /* Here comes the prefix string */ +- if (prefix_len > newcode-code) ++ if (prefix_len > (Py_uintptr_t)(newcode - code)) + FAIL; + code += prefix_len; + /* And here comes the overlap table */ +- if (prefix_len > newcode-code) ++ if (prefix_len > (Py_uintptr_t)(newcode - code)) + FAIL; + /* Each overlap value should be < prefix_len */ + for (i = 0; i < prefix_len; i++) { +@@ -3178,7 +3178,7 @@ _validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups) + case SRE_OP_GROUPREF: + case SRE_OP_GROUPREF_IGNORE: + GET_ARG; +- if (arg >= groups) ++ if (arg >= (size_t)groups) + FAIL; + break; + +@@ -3187,7 +3187,7 @@ _validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups) + '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) ++ if (arg >= (size_t)groups) + FAIL; + GET_SKIP_ADJ(1); + code--; /* The skip is relative to the first arg! */ +@@ -3216,7 +3216,7 @@ _validate_inner(SRE_CODE *code, SRE_CODE *end, Py_ssize_t groups) + to allow arbitrary jumps anywhere in the code; so we just look + for a JUMP opcode preceding our skip target. + */ +- if (skip >= 3 && skip-3 < end-code && ++ if (skip >= 3 && skip-3 < (Py_uintptr_t)(end - code) && + code[skip-3] == SRE_OP_JUMP) + { + VTRACE(("both then and else parts present\n")); +@@ -3327,7 +3327,7 @@ match_getindex(MatchObject* self, PyObject* index) + { + Py_ssize_t i; + +- if (PyInt_Check(index) || PyLong_Check(index)) ++ if (_PyAnyInt_Check(index)) + return PyInt_AsSsize_t(index); + + i = -1; +@@ -3335,7 +3335,7 @@ match_getindex(MatchObject* self, PyObject* index) + if (self->pattern->groupindex) { + index = PyObject_GetItem(self->pattern->groupindex, index); + if (index) { +- if (PyInt_Check(index) || PyLong_Check(index)) ++ if (_PyAnyInt_Check(index)) + i = PyInt_AsSsize_t(index); + Py_DECREF(index); + } else +diff --git a/Modules/_ssl.c b/Modules/_ssl.c +index d0ce913d3d..a96c419260 100644 +--- a/Modules/_ssl.c ++++ b/Modules/_ssl.c +@@ -74,6 +74,7 @@ + #include "openssl/ssl.h" + #include "openssl/err.h" + #include "openssl/rand.h" ++#include "openssl/dh.h" + + /* SSL error object */ + static PyObject *PySSLErrorObject; +diff --git a/Modules/_struct.c b/Modules/_struct.c +index d83d57f2e8..8b97672070 100644 +--- a/Modules/_struct.c ++++ b/Modules/_struct.c +@@ -110,7 +110,7 @@ get_pylong(PyObject *v) + PyObject *r, *w; + int converted = 0; + assert(v != NULL); +- if (!PyInt_Check(v) && !PyLong_Check(v)) { ++ if (!_PyAnyInt_Check(v)) { + PyNumberMethods *m; + /* Not an integer; first try to use __index__ to + convert to an integer. If the __index__ method +@@ -150,7 +150,7 @@ get_pylong(PyObject *v) + v = m->nb_int(v); + if (v == NULL) + return NULL; +- if (!PyInt_Check(v) && !PyLong_Check(v)) { ++ if (!_PyAnyInt_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "__int__ method returned " + "non-integer"); +@@ -169,7 +169,7 @@ get_pylong(PyObject *v) + /* Ensure we own a reference to v. */ + Py_INCREF(v); + +- assert(PyInt_Check(v) || PyLong_Check(v)); ++ assert(_PyAnyInt_Check(v)); + if (PyInt_Check(v)) { + r = PyLong_FromLong(PyInt_AS_LONG(v)); + Py_DECREF(v); +diff --git a/Modules/_testcapimodule.c b/Modules/_testcapimodule.c +index 5902de0782..67488e70e4 100644 +--- a/Modules/_testcapimodule.c ++++ b/Modules/_testcapimodule.c +@@ -1559,6 +1559,89 @@ getargs_et_hash(PyObject *self, PyObject *args) + return result; + } + ++static PyObject * ++get_indices(PyObject *self, PyObject *args) ++{ ++ int result; ++ PySliceObject *slice; ++ Py_ssize_t length, start, stop, step; ++ ++ if (!PyArg_ParseTuple(args, "On", &slice, &length)) ++ return NULL; ++ ++ result = PySlice_GetIndices(slice, length, &start, &stop, &step); ++ ++ if (PyErr_Occurred()) { ++ assert(result == -1); ++ return NULL; ++ } ++ ++ if (result == -1) { ++ Py_RETURN_NONE; ++ } ++ return Py_BuildValue("innn", result, start, stop, step); ++} ++ ++static PyObject * ++parse_tuple_and_keywords(PyObject *self, PyObject *args) ++{ ++ PyObject *sub_args; ++ PyObject *sub_kwargs; ++ const char *sub_format; ++ PyObject *sub_keywords; ++ ++ Py_ssize_t i, size; ++ char *keywords[8 + 1]; /* space for NULL at end */ ++ PyObject *o; ++ ++ int result; ++ PyObject *return_value = NULL; ++ ++ double buffers[8][4]; /* double ensures alignment where necessary */ ++ ++ if (!PyArg_ParseTuple(args, "OOsO:parse_tuple_and_keywords", ++ &sub_args, &sub_kwargs, ++ &sub_format, &sub_keywords)) ++ return NULL; ++ ++ if (!(PyList_CheckExact(sub_keywords) || PyTuple_CheckExact(sub_keywords))) { ++ PyErr_SetString(PyExc_ValueError, ++ "parse_tuple_and_keywords: sub_keywords must be either list or tuple"); ++ return NULL; ++ } ++ ++ memset(buffers, 0, sizeof(buffers)); ++ memset(keywords, 0, sizeof(keywords)); ++ ++ size = PySequence_Fast_GET_SIZE(sub_keywords); ++ if (size > 8) { ++ PyErr_SetString(PyExc_ValueError, ++ "parse_tuple_and_keywords: too many keywords in sub_keywords"); ++ goto exit; ++ } ++ ++ for (i = 0; i < size; i++) { ++ o = PySequence_Fast_GET_ITEM(sub_keywords, i); ++ keywords[i] = PyString_AsString(o); ++ if (keywords[i] == NULL) { ++ goto exit; ++ } ++ } ++ ++ result = PyArg_ParseTupleAndKeywords(sub_args, sub_kwargs, ++ sub_format, keywords, ++ buffers + 0, buffers + 1, buffers + 2, buffers + 3, ++ buffers + 4, buffers + 5, buffers + 6, buffers + 7); ++ ++ if (result) { ++ return_value = Py_None; ++ Py_INCREF(Py_None); ++ } ++ ++exit: ++ return return_value; ++} ++ + #ifdef Py_USING_UNICODE + + static volatile int x; +@@ -1963,7 +2046,8 @@ static int _pending_callback(void *arg) + /* The following requests n callbacks to _pending_callback. It can be + * run from any python thread. + */ +-PyObject *pending_threadfunc(PyObject *self, PyObject *arg) ++static PyObject * ++pending_threadfunc(PyObject *self, PyObject *arg) + { + PyObject *callable; + int r; +@@ -2603,6 +2687,8 @@ static PyMethodDef TestMethods[] = { + #ifdef Py_USING_UNICODE + {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS}, + #endif ++ {"get_indices", get_indices, METH_VARARGS}, ++ {"parse_tuple_and_keywords", parse_tuple_and_keywords, METH_VARARGS}, + {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS}, + {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS}, + {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS, +diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c +index 444c268c0b..c71ffd016a 100644 +--- a/Modules/_tkinter.c ++++ b/Modules/_tkinter.c +@@ -2107,7 +2107,7 @@ Tkapp_GetInt(PyObject *self, PyObject *args) + + if (PyTuple_Size(args) == 1) { + PyObject* o = PyTuple_GetItem(args, 0); +- if (PyInt_Check(o) || PyLong_Check(o)) { ++ if (_PyAnyInt_Check(o)) { + Py_INCREF(o); + return o; + } +diff --git a/Modules/atexitmodule.c b/Modules/atexitmodule.c +deleted file mode 100644 +index 35ebf08ecd..0000000000 ++++ /dev/null +@@ -1,346 +0,0 @@ +-/* +- * atexit - allow programmer to define multiple exit functions to be executed +- * upon normal program termination. +- * +- * Translated from atexit.py by Collin Winter. +- + Copyright 2007 Python Software Foundation. +- */ +- +-#include "Python.h" +- +-/* Forward declaration (for atexit_cleanup) */ +-static PyObject *atexit_clear(PyObject*, PyObject*); +-/* Forward declaration of module object */ +-static struct PyModuleDef atexitmodule; +- +-/* ===================================================================== */ +-/* Callback machinery. */ +- +-typedef struct { +- PyObject *func; +- PyObject *args; +- PyObject *kwargs; +-} atexit_callback; +- +-typedef struct { +- atexit_callback **atexit_callbacks; +- int ncallbacks; +- int callback_len; +-} atexitmodule_state; +- +-#define GET_ATEXIT_STATE(mod) ((atexitmodule_state*)PyModule_GetState(mod)) +- +- +-static void +-atexit_delete_cb(atexitmodule_state *modstate, int i) +-{ +- atexit_callback *cb; +- +- cb = modstate->atexit_callbacks[i]; +- modstate->atexit_callbacks[i] = NULL; +- Py_DECREF(cb->func); +- Py_DECREF(cb->args); +- Py_XDECREF(cb->kwargs); +- PyMem_Free(cb); +-} +- +-/* Clear all callbacks without calling them */ +-static void +-atexit_cleanup(atexitmodule_state *modstate) +-{ +- atexit_callback *cb; +- int i; +- for (i = 0; i < modstate->ncallbacks; i++) { +- cb = modstate->atexit_callbacks[i]; +- if (cb == NULL) +- continue; +- +- atexit_delete_cb(modstate, i); +- } +- modstate->ncallbacks = 0; +-} +- +-/* Installed into pylifecycle.c's atexit mechanism */ +- +-static void +-atexit_callfuncs(void) +-{ +- PyObject *exc_type = NULL, *exc_value, *exc_tb, *r; +- atexit_callback *cb; +- PyObject *module; +- atexitmodule_state *modstate; +- int i; +- +- module = PyState_FindModule(&atexitmodule); +- if (module == NULL) +- return; +- modstate = GET_ATEXIT_STATE(module); +- +- if (modstate->ncallbacks == 0) +- return; +- +- +- for (i = modstate->ncallbacks - 1; i >= 0; i--) +- { +- cb = modstate->atexit_callbacks[i]; +- if (cb == NULL) +- continue; +- +- r = PyObject_Call(cb->func, cb->args, cb->kwargs); +- Py_XDECREF(r); +- if (r == NULL) { +- /* Maintain the last exception, but don't leak if there are +- multiple exceptions. */ +- if (exc_type) { +- Py_DECREF(exc_type); +- Py_XDECREF(exc_value); +- Py_XDECREF(exc_tb); +- } +- PyErr_Fetch(&exc_type, &exc_value, &exc_tb); +- if (!PyErr_GivenExceptionMatches(exc_type, PyExc_SystemExit)) { +- PySys_WriteStderr("Error in atexit._run_exitfuncs:\n"); +- PyErr_NormalizeException(&exc_type, &exc_value, &exc_tb); +- PyErr_Display(exc_type, exc_value, exc_tb); +- } +- } +- } +- +- atexit_cleanup(modstate); +- +- if (exc_type) +- PyErr_Restore(exc_type, exc_value, exc_tb); +-} +- +-/* ===================================================================== */ +-/* Module methods. */ +- +-PyDoc_STRVAR(atexit_register__doc__, +-"register(func, *args, **kwargs) -> func\n\ +-\n\ +-Register a function to be executed upon normal program termination\n\ +-\n\ +- func - function to be called at exit\n\ +- args - optional arguments to pass to func\n\ +- kwargs - optional keyword arguments to pass to func\n\ +-\n\ +- func is returned to facilitate usage as a decorator."); +- +-static PyObject * +-atexit_register(PyObject *self, PyObject *args, PyObject *kwargs) +-{ +- atexitmodule_state *modstate; +- atexit_callback *new_callback; +- PyObject *func = NULL; +- +- modstate = GET_ATEXIT_STATE(self); +- +- if (modstate->ncallbacks >= modstate->callback_len) { +- atexit_callback **r; +- modstate->callback_len += 16; +- r = (atexit_callback**)PyMem_Realloc(modstate->atexit_callbacks, +- sizeof(atexit_callback*) * modstate->callback_len); +- if (r == NULL) +- return PyErr_NoMemory(); +- modstate->atexit_callbacks = r; +- } +- +- if (PyTuple_GET_SIZE(args) == 0) { +- PyErr_SetString(PyExc_TypeError, +- "register() takes at least 1 argument (0 given)"); +- return NULL; +- } +- +- func = PyTuple_GET_ITEM(args, 0); +- if (!PyCallable_Check(func)) { +- PyErr_SetString(PyExc_TypeError, +- "the first argument must be callable"); +- return NULL; +- } +- +- new_callback = PyMem_Malloc(sizeof(atexit_callback)); +- if (new_callback == NULL) +- return PyErr_NoMemory(); +- +- new_callback->args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); +- if (new_callback->args == NULL) { +- PyMem_Free(new_callback); +- return NULL; +- } +- new_callback->func = func; +- new_callback->kwargs = kwargs; +- Py_INCREF(func); +- Py_XINCREF(kwargs); +- +- modstate->atexit_callbacks[modstate->ncallbacks++] = new_callback; +- +- Py_INCREF(func); +- return func; +-} +- +-PyDoc_STRVAR(atexit_run_exitfuncs__doc__, +-"_run_exitfuncs() -> None\n\ +-\n\ +-Run all registered exit functions."); +- +-static PyObject * +-atexit_run_exitfuncs(PyObject *self, PyObject *unused) +-{ +- atexit_callfuncs(); +- if (PyErr_Occurred()) +- return NULL; +- Py_RETURN_NONE; +-} +- +-PyDoc_STRVAR(atexit_clear__doc__, +-"_clear() -> None\n\ +-\n\ +-Clear the list of previously registered exit functions."); +- +-static PyObject * +-atexit_clear(PyObject *self, PyObject *unused) +-{ +- atexit_cleanup(GET_ATEXIT_STATE(self)); +- Py_RETURN_NONE; +-} +- +-PyDoc_STRVAR(atexit_ncallbacks__doc__, +-"_ncallbacks() -> int\n\ +-\n\ +-Return the number of registered exit functions."); +- +-static PyObject * +-atexit_ncallbacks(PyObject *self, PyObject *unused) +-{ +- atexitmodule_state *modstate; +- +- modstate = GET_ATEXIT_STATE(self); +- +- return PyLong_FromSsize_t(modstate->ncallbacks); +-} +- +-static int +-atexit_m_traverse(PyObject *self, visitproc visit, void *arg) +-{ +- int i; +- atexitmodule_state *modstate; +- +- modstate = GET_ATEXIT_STATE(self); +- for (i = 0; i < modstate->ncallbacks; i++) { +- atexit_callback *cb = modstate->atexit_callbacks[i]; +- if (cb == NULL) +- continue; +- Py_VISIT(cb->func); +- Py_VISIT(cb->args); +- Py_VISIT(cb->kwargs); +- } +- return 0; +-} +- +-static int +-atexit_m_clear(PyObject *self) +-{ +- atexitmodule_state *modstate; +- modstate = GET_ATEXIT_STATE(self); +- atexit_cleanup(modstate); +- return 0; +-} +- +-static void +-atexit_free(PyObject *m) +-{ +- atexitmodule_state *modstate; +- modstate = GET_ATEXIT_STATE(m); +- atexit_cleanup(modstate); +- PyMem_Free(modstate->atexit_callbacks); +-} +- +-PyDoc_STRVAR(atexit_unregister__doc__, +-"unregister(func) -> None\n\ +-\n\ +-Unregister an exit function which was previously registered using\n\ +-atexit.register\n\ +-\n\ +- func - function to be unregistered"); +- +-static PyObject * +-atexit_unregister(PyObject *self, PyObject *func) +-{ +- atexitmodule_state *modstate; +- atexit_callback *cb; +- int i, eq; +- +- modstate = GET_ATEXIT_STATE(self); +- +- for (i = 0; i < modstate->ncallbacks; i++) +- { +- cb = modstate->atexit_callbacks[i]; +- if (cb == NULL) +- continue; +- +- eq = PyObject_RichCompareBool(cb->func, func, Py_EQ); +- if (eq < 0) +- return NULL; +- if (eq) +- atexit_delete_cb(modstate, i); +- } +- Py_RETURN_NONE; +-} +- +-static PyMethodDef atexit_methods[] = { +- {"register", (PyCFunction) atexit_register, METH_VARARGS|METH_KEYWORDS, +- atexit_register__doc__}, +- {"_clear", (PyCFunction) atexit_clear, METH_NOARGS, +- atexit_clear__doc__}, +- {"unregister", (PyCFunction) atexit_unregister, METH_O, +- atexit_unregister__doc__}, +- {"_run_exitfuncs", (PyCFunction) atexit_run_exitfuncs, METH_NOARGS, +- atexit_run_exitfuncs__doc__}, +- {"_ncallbacks", (PyCFunction) atexit_ncallbacks, METH_NOARGS, +- atexit_ncallbacks__doc__}, +- {NULL, NULL} /* sentinel */ +-}; +- +-/* ===================================================================== */ +-/* Initialization function. */ +- +-PyDoc_STRVAR(atexit__doc__, +-"allow programmer to define multiple exit functions to be executed\ +-upon normal program termination.\n\ +-\n\ +-Two public functions, register and unregister, are defined.\n\ +-"); +- +- +-static struct PyModuleDef atexitmodule = { +- PyModuleDef_HEAD_INIT, +- "atexit", +- atexit__doc__, +- sizeof(atexitmodule_state), +- atexit_methods, +- NULL, +- atexit_m_traverse, +- atexit_m_clear, +- (freefunc)atexit_free +-}; +- +-PyMODINIT_FUNC +-PyInit_atexit(void) +-{ +- PyObject *m; +- atexitmodule_state *modstate; +- +- m = PyModule_Create(&atexitmodule); +- if (m == NULL) +- return NULL; +- +- modstate = GET_ATEXIT_STATE(m); +- modstate->callback_len = 32; +- modstate->ncallbacks = 0; +- modstate->atexit_callbacks = PyMem_New(atexit_callback*, +- modstate->callback_len); +- if (modstate->atexit_callbacks == NULL) +- return NULL; +- +- _Py_PyAtExit(atexit_callfuncs); +- return m; +-} +diff --git a/Modules/audioop.c b/Modules/audioop.c +index ad7336c7f9..91f585c8f0 100644 +--- a/Modules/audioop.c ++++ b/Modules/audioop.c +@@ -25,17 +25,25 @@ typedef short PyInt16; + #endif + + static const int maxvals[] = {0, 0x7F, 0x7FFF, 0x7FFFFF, 0x7FFFFFFF}; +-static const int minvals[] = {0, -0x80, -0x8000, -0x800000, -0x80000000}; ++/* -1 trick is needed on Windows to support -0x80000000 without a warning */ ++static const int minvals[] = {0, -0x80, -0x8000, -0x800000, -0x7FFFFFFF-1}; + static const unsigned int masks[] = {0, 0xFF, 0xFFFF, 0xFFFFFF, 0xFFFFFFFF}; + + static int + fbound(double val, double minval, double maxval) + { +- if (val > maxval) ++ if (val > maxval) { + val = maxval; +- else if (val < minval + 1) ++ } ++ else if (val < minval + 1.0) { + val = minval; +- return val; ++ } ++ ++ /* Round towards minus infinity (-inf) */ ++ val = floor(val); ++ ++ /* Cast double to integer: round towards zero */ ++ return (int)val; + } + + +@@ -386,7 +394,9 @@ audioop_minmax(PyObject *self, PyObject *args) + signed char *cp; + int len, size, val = 0; + int i; +- int min = 0x7fffffff, max = -0x80000000; ++ /* -1 trick below is needed on Windows to support -0x80000000 without ++ a warning */ ++ int min = 0x7fffffff, max = -0x7FFFFFFF-1; + + if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size)) + return NULL; +@@ -793,8 +803,8 @@ audioop_mul(PyObject *self, PyObject *args) + if ( size == 1 ) val = (int)*CHARP(cp, i); + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = (int)*LONGP(cp, i); +- fval = (double)val*factor; +- val = (int)floor(fbound(fval, minval, maxval)); ++ fval = (double)val * factor; ++ val = fbound(fval, minval, maxval); + if ( size == 1 ) *CHARP(ncp, i) = (signed char)val; + else if ( size == 2 ) *SHORTP(ncp, i) = (short)val; + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)val; +@@ -837,8 +847,8 @@ audioop_tomono(PyObject *self, PyObject *args) + if ( size == 1 ) val2 = (int)*CHARP(cp, i+1); + else if ( size == 2 ) val2 = (int)*SHORTP(cp, i+2); + else if ( size == 4 ) val2 = (int)*LONGP(cp, i+4); +- fval = (double)val1*fac1 + (double)val2*fac2; +- val1 = (int)floor(fbound(fval, minval, maxval)); ++ fval = (double)val1 * fac1 + (double)val2 * fac2; ++ val1 = fbound(fval, minval, maxval); + if ( size == 1 ) *CHARP(ncp, i/2) = (signed char)val1; + else if ( size == 2 ) *SHORTP(ncp, i/2) = (short)val1; + else if ( size == 4 ) *LONGP(ncp, i/2)= (Py_Int32)val1; +@@ -881,11 +891,11 @@ audioop_tostereo(PyObject *self, PyObject *args) + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = (int)*LONGP(cp, i); + +- fval = (double)val*fac1; +- val1 = (int)floor(fbound(fval, minval, maxval)); ++ fval = (double)val * fac1; ++ val1 = fbound(fval, minval, maxval); + +- fval = (double)val*fac2; +- val2 = (int)floor(fbound(fval, minval, maxval)); ++ fval = (double)val * fac2; ++ val2 = fbound(fval, minval, maxval); + + if ( size == 1 ) *CHARP(ncp, i*2) = (signed char)val1; + else if ( size == 2 ) *SHORTP(ncp, i*2) = (short)val1; +@@ -944,7 +954,7 @@ audioop_add(PyObject *self, PyObject *args) + else { + double fval = (double)val1 + (double)val2; + /* truncate in case of overflow */ +- newval = (int)floor(fbound(fval, minval, maxval)); ++ newval = fbound(fval, minval, maxval); + } + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval; +diff --git a/Modules/cjkcodecs/multibytecodec.c b/Modules/cjkcodecs/multibytecodec.c +index 8901b42e41..4b482bf9e2 100644 +--- a/Modules/cjkcodecs/multibytecodec.c ++++ b/Modules/cjkcodecs/multibytecodec.c +@@ -310,8 +310,7 @@ multibytecodec_encerror(MultibyteCodec *codec, + + if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || + !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) || +- !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) || +- PyLong_Check(PyTuple_GET_ITEM(retobj, 1)))) { ++ !_PyAnyInt_Check(PyTuple_GET_ITEM(retobj, 1))) { + PyErr_SetString(PyExc_TypeError, + "encoding error handler must return " + "(unicode, int) tuple"); +@@ -430,8 +429,7 @@ multibytecodec_decerror(MultibyteCodec *codec, + + if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || + !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) || +- !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) || +- PyLong_Check(PyTuple_GET_ITEM(retobj, 1)))) { ++ !_PyAnyInt_Check(PyTuple_GET_ITEM(retobj, 1))) { + PyErr_SetString(PyExc_TypeError, + "decoding error handler must return " + "(unicode, int) tuple"); +diff --git a/Modules/datetimemodule.c b/Modules/datetimemodule.c +index e818c5cfdc..c0b7102de2 100644 +--- a/Modules/datetimemodule.c ++++ b/Modules/datetimemodule.c +@@ -1537,7 +1537,7 @@ delta_to_microseconds(PyDateTime_Delta *self) + if (x2 == NULL) + goto Done; + result = PyNumber_Add(x1, x2); +- assert(result == NULL || PyInt_CheckExact(result) || PyLong_CheckExact(result)); ++ assert(result == NULL || _PyAnyInt_CheckExact(result)); + + Done: + Py_XDECREF(x1); +@@ -1560,7 +1560,7 @@ microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type) + PyObject *num = NULL; + PyObject *result = NULL; + +- assert(PyInt_CheckExact(pyus) || PyLong_CheckExact(pyus)); ++ assert(_PyAnyInt_CheckExact(pyus)); + tuple = PyNumber_Divmod(pyus, us_per_second); + if (tuple == NULL) + goto Done; +@@ -1803,11 +1803,11 @@ delta_multiply(PyObject *left, PyObject *right) + + if (PyDelta_Check(left)) { + /* delta * ??? */ +- if (PyInt_Check(right) || PyLong_Check(right)) ++ if (_PyAnyInt_Check(right)) + result = multiply_int_timedelta(right, + (PyDateTime_Delta *) left); + } +- else if (PyInt_Check(left) || PyLong_Check(left)) ++ else if (_PyAnyInt_Check(left)) + result = multiply_int_timedelta(left, + (PyDateTime_Delta *) right); + +@@ -1823,7 +1823,7 @@ delta_divide(PyObject *left, PyObject *right) + + if (PyDelta_Check(left)) { + /* delta * ??? */ +- if (PyInt_Check(right) || PyLong_Check(right)) ++ if (_PyAnyInt_Check(right)) + result = divide_timedelta_int( + (PyDateTime_Delta *)left, + right); +@@ -1852,14 +1852,14 @@ accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor, + + assert(num != NULL); + +- if (PyInt_Check(num) || PyLong_Check(num)) { ++ if (_PyAnyInt_Check(num)) { + prod = PyNumber_Multiply(factor, num); + if (prod == NULL) + return NULL; +- assert(PyInt_CheckExact(prod) || PyLong_CheckExact(prod)); ++ assert(_PyAnyInt_CheckExact(prod)); + sum = PyNumber_Add(sofar, prod); + Py_DECREF(prod); +- assert(sum == NULL || PyInt_CheckExact(sum) || PyLong_CheckExact(sum)); ++ assert(sum == NULL || _PyAnyInt_CheckExact(sum)); + return sum; + } + +@@ -1902,7 +1902,7 @@ accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor, + * fractional part requires float arithmetic, and may + * lose a little info. + */ +- assert(PyInt_CheckExact(factor) || PyLong_CheckExact(factor)); ++ assert(_PyAnyInt_CheckExact(factor)); + if (PyInt_Check(factor)) + dnum = (double)PyInt_AsLong(factor); + else +@@ -1920,7 +1920,7 @@ accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor, + Py_DECREF(sum); + Py_DECREF(x); + *leftover += fracpart; +- assert(y == NULL || PyInt_CheckExact(y) || PyLong_CheckExact(y)); ++ assert(y == NULL || _PyAnyInt_CheckExact(y)); + return y; + } + +diff --git a/Modules/dlmodule.c b/Modules/dlmodule.c +index 7a6686e3a6..3f15048700 100644 +--- a/Modules/dlmodule.c ++++ b/Modules/dlmodule.c +@@ -107,7 +107,7 @@ dl_call(dlobject *xp, PyObject *args) + } + for (i = 1; i < n; i++) { + PyObject *v = PyTuple_GetItem(args, i); +- if (PyInt_Check(v) || PyLong_Check(v)) { ++ if (_PyAnyInt_Check(v)) { + alist[i-1] = PyInt_AsLong(v); + if (alist[i-1] == -1 && PyErr_Occurred()) + return NULL; +diff --git a/Modules/expat/expat.h b/Modules/expat/expat.h +index d0735bb5c6..174c3fafda 100644 +--- a/Modules/expat/expat.h ++++ b/Modules/expat/expat.h +@@ -264,7 +264,7 @@ XML_ParserCreate_MM(const XML_Char *encoding, + const XML_Char *namespaceSeparator); + + /* Prepare a parser object to be re-used. This is particularly +- valuable when memory allocation overhead is disproportionatly high, ++ valuable when memory allocation overhead is disproportionately high, + such as when a large number of small documnents need to be parsed. + All handlers are cleared from the parser, except for the + unknownEncodingHandler. The parser's external state is re-initialized +@@ -1076,7 +1076,7 @@ XML_GetFeatureList(void); + */ + #define XML_MAJOR_VERSION 2 + #define XML_MINOR_VERSION 2 +-#define XML_MICRO_VERSION 4 ++#define XML_MICRO_VERSION 6 + + #ifdef __cplusplus + } +diff --git a/Modules/expat/expat_external.h b/Modules/expat/expat_external.h +index 8110285649..629483a91b 100644 +--- a/Modules/expat/expat_external.h ++++ b/Modules/expat/expat_external.h +@@ -35,12 +35,8 @@ + + /* External API definitions */ + +-/* Namespace external symbols to allow multiple libexpat version to +- co-exist. */ +-#include "pyexpatns.h" +- + #if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__) +-#define XML_USE_MSC_EXTENSIONS 1 ++# define XML_USE_MSC_EXTENSIONS 1 + #endif + + /* Expat tries very hard to make the API boundary very specifically +@@ -66,11 +62,11 @@ + system headers may assume the cdecl convention. + */ + #ifndef XMLCALL +-#if defined(_MSC_VER) +-#define XMLCALL __cdecl +-#elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER) +-#define XMLCALL __attribute__((cdecl)) +-#else ++# if defined(_MSC_VER) ++# define XMLCALL __cdecl ++# elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER) ++# 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 +@@ -81,41 +77,41 @@ + pre-processor and how to specify the same calling convention as the + platform's malloc() implementation. + */ +-#define XMLCALL +-#endif ++# define XMLCALL ++# endif + #endif /* not defined XMLCALL */ + + + #if !defined(XML_STATIC) && !defined(XMLIMPORT) +-#ifndef XML_BUILDING_EXPAT ++# ifndef XML_BUILDING_EXPAT + /* using Expat from an application */ + +-#ifdef XML_USE_MSC_EXTENSIONS +-#define XMLIMPORT __declspec(dllimport) +-#endif ++# ifdef XML_USE_MSC_EXTENSIONS ++# define XMLIMPORT __declspec(dllimport) ++# endif + +-#endif ++# endif + #endif /* not defined XML_STATIC */ + + #if !defined(XMLIMPORT) && defined(__GNUC__) && (__GNUC__ >= 4) +-#define XMLIMPORT __attribute__ ((visibility ("default"))) ++# define XMLIMPORT __attribute__ ((visibility ("default"))) + #endif + + /* If we didn't define it above, define it away: */ + #ifndef XMLIMPORT +-#define XMLIMPORT ++# define XMLIMPORT + #endif + + #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)) +-#define XML_ATTR_MALLOC __attribute__((__malloc__)) ++# define XML_ATTR_MALLOC __attribute__((__malloc__)) + #else +-#define XML_ATTR_MALLOC ++# define XML_ATTR_MALLOC + #endif + + #if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +-#define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) ++# define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) + #else +-#define XML_ATTR_ALLOC_SIZE(x) ++# define XML_ATTR_ALLOC_SIZE(x) + #endif + + #define XMLPARSEAPI(type) XMLIMPORT type XMLCALL +@@ -125,33 +121,35 @@ extern "C" { + #endif + + #ifdef XML_UNICODE_WCHAR_T +-# define XML_UNICODE ++# ifndef XML_UNICODE ++# define XML_UNICODE ++# endif + # if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2) + # error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc" + # endif + #endif + + #ifdef XML_UNICODE /* Information is UTF-16 encoded. */ +-#ifdef XML_UNICODE_WCHAR_T ++# ifdef XML_UNICODE_WCHAR_T + typedef wchar_t XML_Char; + typedef wchar_t XML_LChar; +-#else ++# else + typedef unsigned short XML_Char; + typedef char XML_LChar; +-#endif /* XML_UNICODE_WCHAR_T */ ++# 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 ++# if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400 + typedef __int64 XML_Index; + typedef unsigned __int64 XML_Size; +-#else ++# else + typedef long long XML_Index; + typedef unsigned long long XML_Size; +-#endif ++# endif + #else + typedef long XML_Index; + typedef unsigned long XML_Size; +diff --git a/Modules/expat/internal.h b/Modules/expat/internal.h +index 3c5d6e913d..e33fdcb023 100644 +--- a/Modules/expat/internal.h ++++ b/Modules/expat/internal.h +@@ -116,7 +116,7 @@ extern "C" { + + + void +-align_limit_to_full_utf8_characters(const char * from, const char ** fromLimRef); ++_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef); + + + #ifdef __cplusplus +diff --git a/Modules/expat/loadlibrary.c b/Modules/expat/loadlibrary.c +index 452ae92db2..35fdf98bce 100644 +--- a/Modules/expat/loadlibrary.c ++++ b/Modules/expat/loadlibrary.c +@@ -84,7 +84,7 @@ HMODULE _Expat_LoadLibrary(LPCTSTR filename) + /* Get a handle to kernel32 so we can access it's functions at runtime */ + HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32")); + if(!hKernel32) +- return NULL; ++ return NULL; /* LCOV_EXCL_LINE */ + + /* Attempt to find LoadLibraryEx() which is only available on Windows 2000 + and above */ +diff --git a/Modules/expat/siphash.h b/Modules/expat/siphash.h +index 581872df7b..4d6786d783 100644 +--- a/Modules/expat/siphash.h ++++ b/Modules/expat/siphash.h +@@ -11,6 +11,12 @@ + * -------------------------------------------------------------------------- + * HISTORY: + * ++ * 2018-07-08 (Anton Maklakov) ++ * - Add "fall through" markers for GCC's -Wimplicit-fallthrough ++ * ++ * 2017-11-03 (Sebastian Pipping) ++ * - Hide sip_tobin and sip_binof unless SIPHASH_TOBIN macro is defined ++ * + * 2017-07-25 (Vadim Zeitlin) + * - Fix use of SIPHASH_MAIN macro + * +@@ -151,6 +157,8 @@ static struct sipkey *sip_tokey(struct sipkey *key, const void *src) { + } /* sip_tokey() */ + + ++#ifdef SIPHASH_TOBIN ++ + #define sip_binof(v) sip_tobin((unsigned char[8]){ 0 }, (v)) + + static void *sip_tobin(void *dst, uint64_t u64) { +@@ -158,6 +166,8 @@ static void *sip_tobin(void *dst, uint64_t u64) { + return dst; + } /* sip_tobin() */ + ++#endif /* SIPHASH_TOBIN */ ++ + + static void sip_round(struct siphash *H, const int rounds) { + int i; +@@ -231,12 +241,19 @@ static uint64_t sip24_final(struct siphash *H) { + + switch (left) { + case 7: b |= (uint64_t)H->buf[6] << 48; ++ /* fall through */ + case 6: b |= (uint64_t)H->buf[5] << 40; ++ /* fall through */ + case 5: b |= (uint64_t)H->buf[4] << 32; ++ /* fall through */ + case 4: b |= (uint64_t)H->buf[3] << 24; ++ /* fall through */ + case 3: b |= (uint64_t)H->buf[2] << 16; ++ /* fall through */ + case 2: b |= (uint64_t)H->buf[1] << 8; ++ /* fall through */ + case 1: b |= (uint64_t)H->buf[0] << 0; ++ /* fall through */ + case 0: break; + } + +diff --git a/Modules/expat/xmlparse.c b/Modules/expat/xmlparse.c +index 0df68830f0..c4f3ffc215 100644 +--- a/Modules/expat/xmlparse.c ++++ b/Modules/expat/xmlparse.c +@@ -1,4 +1,4 @@ +-/* 8c6b2be7c6281da65ce05218fc15c339f02a811706340824ab596aa86e1fd51a (2.2.4+) ++/* 19ac4776051591216f1874e34ee99b6a43a3784c8bd7d70efeb9258dd22b906a (2.2.6+) + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| +@@ -161,6 +161,9 @@ typedef char ICHAR; + /* 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)) + ++/* Do safe (NULL-aware) pointer arithmetic */ ++#define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0) ++ + /* Handle the case where memmove() doesn't exist. */ + #ifndef HAVE_MEMMOVE + #ifdef HAVE_BCOPY +@@ -470,7 +473,7 @@ 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 */ ++/* do not call if m_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); +@@ -542,7 +545,7 @@ parserInit(XML_Parser parser, const XML_Char *encodingName); + : ((*((pool)->ptr)++ = c), 1)) + + struct XML_ParserStruct { +- /* The first member must be userData so that the XML_GetUserData ++ /* The first member must be m_userData so that the XML_GetUserData + macro works. */ + void *m_userData; + void *m_handlerArg; +@@ -552,7 +555,7 @@ struct XML_ParserStruct { + const char *m_bufferPtr; + /* past last character to be parsed */ + char *m_bufferEnd; +- /* allocated end of buffer */ ++ /* allocated end of m_buffer */ + const char *m_bufferLim; + XML_Index m_parseEndByteIndex; + const char *m_parseEndPtr; +@@ -644,113 +647,10 @@ struct XML_ParserStruct { + unsigned long m_hash_secret_salt; + }; + +-#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 attInfo (parser->m_attInfo) +-#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 */ +-#define hash_secret_salt (parser->m_hash_secret_salt) ++#define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s))) ++#define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p),(s))) ++#define FREE(parser, p) (parser->m_mem.free_fcn((p))) ++ + + XML_Parser XMLCALL + XML_ParserCreate(const XML_Char *encodingName) +@@ -776,6 +676,9 @@ static const XML_Char implicitContext[] = { + }; + + ++/* To avoid warnings about unused functions: */ ++#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) ++ + #if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) + + /* Obtain entropy on Linux 3.17+ */ +@@ -841,6 +744,8 @@ writeRandomBytes_dev_urandom(void * target, size_t count) { + + #endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */ + ++#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */ ++ + + #if defined(HAVE_ARC4RANDOM) + +@@ -942,6 +847,8 @@ generate_hash_secret_salt(XML_Parser parser) + { + unsigned long entropy; + (void)parser; ++ ++ /* "Failproof" high quality providers: */ + #if defined(HAVE_ARC4RANDOM_BUF) + arc4random_buf(&entropy, sizeof(entropy)); + return ENTROPY_DEBUG("arc4random_buf", entropy); +@@ -990,9 +897,9 @@ static XML_Bool /* only valid for root parser */ + startParsing(XML_Parser parser) + { + /* hash functions must be initialized before setContext() is called */ +- if (hash_secret_salt == 0) +- hash_secret_salt = generate_hash_secret_salt(parser); +- if (ns) { ++ if (parser->m_hash_secret_salt == 0) ++ parser->m_hash_secret_salt = generate_hash_secret_salt(parser); ++ if (parser->m_ns) { + /* implicit context only set for root parser, since child + parsers (i.e. external entity parsers) will inherit it + */ +@@ -1042,85 +949,85 @@ parserCreate(const XML_Char *encodingName, + if (!parser) + return parser; + +- buffer = NULL; +- bufferLim = NULL; ++ parser->m_buffer = NULL; ++ parser->m_bufferLim = NULL; + +- attsSize = INIT_ATTS_SIZE; +- atts = (ATTRIBUTE *)MALLOC(attsSize * sizeof(ATTRIBUTE)); +- if (atts == NULL) { +- FREE(parser); ++ parser->m_attsSize = INIT_ATTS_SIZE; ++ parser->m_atts = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE)); ++ if (parser->m_atts == NULL) { ++ FREE(parser, parser); + return NULL; + } + #ifdef XML_ATTR_INFO +- attInfo = (XML_AttrInfo*)MALLOC(attsSize * sizeof(XML_AttrInfo)); +- if (attInfo == NULL) { +- FREE(atts); +- FREE(parser); ++ parser->m_attInfo = (XML_AttrInfo*)MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo)); ++ if (parser->m_attInfo == NULL) { ++ FREE(parser, parser->m_atts); ++ FREE(parser, parser); + return NULL; + } + #endif +- dataBuf = (XML_Char *)MALLOC(INIT_DATA_BUF_SIZE * sizeof(XML_Char)); +- if (dataBuf == NULL) { +- FREE(atts); ++ parser->m_dataBuf = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char)); ++ if (parser->m_dataBuf == NULL) { ++ FREE(parser, parser->m_atts); + #ifdef XML_ATTR_INFO +- FREE(attInfo); ++ FREE(parser, parser->m_attInfo); + #endif +- FREE(parser); ++ FREE(parser, parser); + return NULL; + } +- dataBufEnd = dataBuf + INIT_DATA_BUF_SIZE; ++ parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE; + + if (dtd) +- _dtd = dtd; ++ parser->m_dtd = dtd; + else { +- _dtd = dtdCreate(&parser->m_mem); +- if (_dtd == NULL) { +- FREE(dataBuf); +- FREE(atts); ++ parser->m_dtd = dtdCreate(&parser->m_mem); ++ if (parser->m_dtd == NULL) { ++ FREE(parser, parser->m_dataBuf); ++ FREE(parser, parser->m_atts); + #ifdef XML_ATTR_INFO +- FREE(attInfo); ++ FREE(parser, parser->m_attInfo); + #endif +- FREE(parser); ++ FREE(parser, parser); + return NULL; + } + } + +- freeBindingList = NULL; +- freeTagList = NULL; +- freeInternalEntities = NULL; ++ parser->m_freeBindingList = NULL; ++ parser->m_freeTagList = NULL; ++ parser->m_freeInternalEntities = NULL; + +- groupSize = 0; +- groupConnector = NULL; ++ parser->m_groupSize = 0; ++ parser->m_groupConnector = NULL; + +- unknownEncodingHandler = NULL; +- unknownEncodingHandlerData = NULL; ++ parser->m_unknownEncodingHandler = NULL; ++ parser->m_unknownEncodingHandlerData = NULL; + +- namespaceSeparator = ASCII_EXCL; +- ns = XML_FALSE; +- ns_triplets = XML_FALSE; ++ parser->m_namespaceSeparator = ASCII_EXCL; ++ parser->m_ns = XML_FALSE; ++ parser->m_ns_triplets = XML_FALSE; + +- nsAtts = NULL; +- nsAttsVersion = 0; +- nsAttsPower = 0; ++ parser->m_nsAtts = NULL; ++ parser->m_nsAttsVersion = 0; ++ parser->m_nsAttsPower = 0; + +- protocolEncodingName = NULL; ++ parser->m_protocolEncodingName = NULL; + +- poolInit(&tempPool, &(parser->m_mem)); +- poolInit(&temp2Pool, &(parser->m_mem)); ++ poolInit(&parser->m_tempPool, &(parser->m_mem)); ++ poolInit(&parser->m_temp2Pool, &(parser->m_mem)); + parserInit(parser, encodingName); + +- if (encodingName && !protocolEncodingName) { ++ if (encodingName && !parser->m_protocolEncodingName) { + XML_ParserFree(parser); + return NULL; + } + + if (nameSep) { +- ns = XML_TRUE; +- internalEncoding = XmlGetInternalEncodingNS(); +- namespaceSeparator = *nameSep; ++ parser->m_ns = XML_TRUE; ++ parser->m_internalEncoding = XmlGetInternalEncodingNS(); ++ parser->m_namespaceSeparator = *nameSep; + } + else { +- internalEncoding = XmlGetInternalEncoding(); ++ parser->m_internalEncoding = XmlGetInternalEncoding(); + } + + return parser; +@@ -1129,85 +1036,85 @@ parserCreate(const XML_Char *encodingName, + static void + parserInit(XML_Parser parser, const XML_Char *encodingName) + { +- processor = prologInitProcessor; +- XmlPrologStateInit(&prologState); ++ parser->m_processor = prologInitProcessor; ++ XmlPrologStateInit(&parser->m_prologState); + if (encodingName != NULL) { +- protocolEncodingName = copyString(encodingName, &(parser->m_mem)); +- } +- 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; ++ parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem)); ++ } ++ parser->m_curBase = NULL; ++ XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0); ++ parser->m_userData = NULL; ++ parser->m_handlerArg = NULL; ++ parser->m_startElementHandler = NULL; ++ parser->m_endElementHandler = NULL; ++ parser->m_characterDataHandler = NULL; ++ parser->m_processingInstructionHandler = NULL; ++ parser->m_commentHandler = NULL; ++ parser->m_startCdataSectionHandler = NULL; ++ parser->m_endCdataSectionHandler = NULL; ++ parser->m_defaultHandler = NULL; ++ parser->m_startDoctypeDeclHandler = NULL; ++ parser->m_endDoctypeDeclHandler = NULL; ++ parser->m_unparsedEntityDeclHandler = NULL; ++ parser->m_notationDeclHandler = NULL; ++ parser->m_startNamespaceDeclHandler = NULL; ++ parser->m_endNamespaceDeclHandler = NULL; ++ parser->m_notStandaloneHandler = NULL; ++ parser->m_externalEntityRefHandler = NULL; ++ parser->m_externalEntityRefHandlerArg = parser; ++ parser->m_skippedEntityHandler = NULL; ++ parser->m_elementDeclHandler = NULL; ++ parser->m_attlistDeclHandler = NULL; ++ parser->m_entityDeclHandler = NULL; ++ parser->m_xmlDeclHandler = NULL; ++ parser->m_bufferPtr = parser->m_buffer; ++ parser->m_bufferEnd = parser->m_buffer; ++ parser->m_parseEndByteIndex = 0; ++ parser->m_parseEndPtr = NULL; ++ parser->m_declElementType = NULL; ++ parser->m_declAttributeId = NULL; ++ parser->m_declEntity = NULL; ++ parser->m_doctypeName = NULL; ++ parser->m_doctypeSysid = NULL; ++ parser->m_doctypePubid = NULL; ++ parser->m_declAttributeType = NULL; ++ parser->m_declNotationName = NULL; ++ parser->m_declNotationPublicId = NULL; ++ parser->m_declAttributeIsCdata = XML_FALSE; ++ parser->m_declAttributeIsId = XML_FALSE; ++ memset(&parser->m_position, 0, sizeof(POSITION)); ++ parser->m_errorCode = XML_ERROR_NONE; ++ parser->m_eventPtr = NULL; ++ parser->m_eventEndPtr = NULL; ++ parser->m_positionPtr = NULL; ++ parser->m_openInternalEntities = NULL; ++ parser->m_defaultExpandInternalEntities = XML_TRUE; ++ parser->m_tagLevel = 0; ++ parser->m_tagStack = NULL; ++ parser->m_inheritedBindings = NULL; ++ parser->m_nSpecifiedAtts = 0; ++ parser->m_unknownEncodingMem = NULL; ++ parser->m_unknownEncodingRelease = NULL; ++ parser->m_unknownEncodingData = NULL; ++ parser->m_parentParser = NULL; ++ parser->m_parsingStatus.parsing = XML_INITIALIZED; + #ifdef XML_DTD +- isParamEntity = XML_FALSE; +- useForeignDTD = XML_FALSE; +- paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; ++ parser->m_isParamEntity = XML_FALSE; ++ parser->m_useForeignDTD = XML_FALSE; ++ parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; + #endif +- hash_secret_salt = 0; ++ parser->m_hash_secret_salt = 0; + } + +-/* moves list of bindings to freeBindingList */ ++/* moves list of bindings to m_freeBindingList */ + static void FASTCALL + moveToFreeBindingList(XML_Parser parser, BINDING *bindings) + { + while (bindings) { + BINDING *b = bindings; + bindings = bindings->nextTagBinding; +- b->nextTagBinding = freeBindingList; +- freeBindingList = b; ++ b->nextTagBinding = parser->m_freeBindingList; ++ parser->m_freeBindingList = b; + } + } + +@@ -1220,36 +1127,36 @@ XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) + if (parser == NULL) + return XML_FALSE; + +- if (parentParser) ++ if (parser->m_parentParser) + return XML_FALSE; +- /* move tagStack to freeTagList */ +- tStk = tagStack; ++ /* move m_tagStack to m_freeTagList */ ++ tStk = parser->m_tagStack; + while (tStk) { + TAG *tag = tStk; + tStk = tStk->parent; +- tag->parent = freeTagList; ++ tag->parent = parser->m_freeTagList; + moveToFreeBindingList(parser, tag->bindings); + tag->bindings = NULL; +- freeTagList = tag; ++ parser->m_freeTagList = tag; + } +- /* move openInternalEntities to freeInternalEntities */ +- openEntityList = openInternalEntities; ++ /* move m_openInternalEntities to m_freeInternalEntities */ ++ openEntityList = parser->m_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); +- FREE((void *)protocolEncodingName); +- protocolEncodingName = NULL; ++ openEntity->next = parser->m_freeInternalEntities; ++ parser->m_freeInternalEntities = openEntity; ++ } ++ moveToFreeBindingList(parser, parser->m_inheritedBindings); ++ FREE(parser, parser->m_unknownEncodingMem); ++ if (parser->m_unknownEncodingRelease) ++ parser->m_unknownEncodingRelease(parser->m_unknownEncodingData); ++ poolClear(&parser->m_tempPool); ++ poolClear(&parser->m_temp2Pool); ++ FREE(parser, (void *)parser->m_protocolEncodingName); ++ parser->m_protocolEncodingName = NULL; + parserInit(parser, encodingName); +- dtdReset(_dtd, &parser->m_mem); ++ dtdReset(parser->m_dtd, &parser->m_mem); + return XML_TRUE; + } + +@@ -1262,19 +1169,19 @@ XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) + 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) ++ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return XML_STATUS_ERROR; + + /* Get rid of any previous encoding name */ +- FREE((void *)protocolEncodingName); ++ FREE(parser, (void *)parser->m_protocolEncodingName); + + if (encodingName == NULL) + /* No new encoding name */ +- protocolEncodingName = NULL; ++ parser->m_protocolEncodingName = NULL; + else { + /* Copy the new encoding name into allocated memory */ +- protocolEncodingName = copyString(encodingName, &(parser->m_mem)); +- if (!protocolEncodingName) ++ parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem)); ++ if (!parser->m_protocolEncodingName) + return XML_STATUS_ERROR; + } + return XML_STATUS_OK; +@@ -1331,44 +1238,44 @@ XML_ExternalEntityParserCreate(XML_Parser oldParser, + return NULL; + + /* Stash the original parser contents on the stack */ +- oldDtd = _dtd; +- oldStartElementHandler = startElementHandler; +- oldEndElementHandler = endElementHandler; +- oldCharacterDataHandler = characterDataHandler; +- oldProcessingInstructionHandler = processingInstructionHandler; +- oldCommentHandler = commentHandler; +- oldStartCdataSectionHandler = startCdataSectionHandler; +- oldEndCdataSectionHandler = endCdataSectionHandler; +- oldDefaultHandler = defaultHandler; +- oldUnparsedEntityDeclHandler = unparsedEntityDeclHandler; +- oldNotationDeclHandler = notationDeclHandler; +- oldStartNamespaceDeclHandler = startNamespaceDeclHandler; +- oldEndNamespaceDeclHandler = endNamespaceDeclHandler; +- oldNotStandaloneHandler = notStandaloneHandler; +- oldExternalEntityRefHandler = externalEntityRefHandler; +- oldSkippedEntityHandler = skippedEntityHandler; +- oldUnknownEncodingHandler = unknownEncodingHandler; +- oldElementDeclHandler = elementDeclHandler; +- oldAttlistDeclHandler = attlistDeclHandler; +- oldEntityDeclHandler = entityDeclHandler; +- oldXmlDeclHandler = xmlDeclHandler; +- oldDeclElementType = declElementType; +- +- oldUserData = userData; +- oldHandlerArg = handlerArg; +- oldDefaultExpandInternalEntities = defaultExpandInternalEntities; +- oldExternalEntityRefHandlerArg = externalEntityRefHandlerArg; ++ oldDtd = parser->m_dtd; ++ oldStartElementHandler = parser->m_startElementHandler; ++ oldEndElementHandler = parser->m_endElementHandler; ++ oldCharacterDataHandler = parser->m_characterDataHandler; ++ oldProcessingInstructionHandler = parser->m_processingInstructionHandler; ++ oldCommentHandler = parser->m_commentHandler; ++ oldStartCdataSectionHandler = parser->m_startCdataSectionHandler; ++ oldEndCdataSectionHandler = parser->m_endCdataSectionHandler; ++ oldDefaultHandler = parser->m_defaultHandler; ++ oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler; ++ oldNotationDeclHandler = parser->m_notationDeclHandler; ++ oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler; ++ oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler; ++ oldNotStandaloneHandler = parser->m_notStandaloneHandler; ++ oldExternalEntityRefHandler = parser->m_externalEntityRefHandler; ++ oldSkippedEntityHandler = parser->m_skippedEntityHandler; ++ oldUnknownEncodingHandler = parser->m_unknownEncodingHandler; ++ oldElementDeclHandler = parser->m_elementDeclHandler; ++ oldAttlistDeclHandler = parser->m_attlistDeclHandler; ++ oldEntityDeclHandler = parser->m_entityDeclHandler; ++ oldXmlDeclHandler = parser->m_xmlDeclHandler; ++ oldDeclElementType = parser->m_declElementType; ++ ++ oldUserData = parser->m_userData; ++ oldHandlerArg = parser->m_handlerArg; ++ oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities; ++ oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg; + #ifdef XML_DTD +- oldParamEntityParsing = paramEntityParsing; +- oldInEntityValue = prologState.inEntityValue; ++ oldParamEntityParsing = parser->m_paramEntityParsing; ++ oldInEntityValue = parser->m_prologState.inEntityValue; + #endif +- oldns_triplets = ns_triplets; ++ oldns_triplets = parser->m_ns_triplets; + /* Note that the new parser shares the same hash secret as the old + parser, so that dtdCopy and copyEntityTable can lookup values + from hash tables associated with either parser without us having + to worry which hash secrets each table has. + */ +- oldhash_secret_salt = hash_secret_salt; ++ oldhash_secret_salt = parser->m_hash_secret_salt; + + #ifdef XML_DTD + if (!context) +@@ -1380,9 +1287,9 @@ XML_ExternalEntityParserCreate(XML_Parser oldParser, + here. This makes this function more painful to follow than it + would be otherwise. + */ +- if (ns) { ++ if (parser->m_ns) { + XML_Char tmp[2]; +- *tmp = namespaceSeparator; ++ *tmp = parser->m_namespaceSeparator; + parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd); + } + else { +@@ -1392,62 +1299,62 @@ XML_ExternalEntityParserCreate(XML_Parser oldParser, + 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; ++ parser->m_startElementHandler = oldStartElementHandler; ++ parser->m_endElementHandler = oldEndElementHandler; ++ parser->m_characterDataHandler = oldCharacterDataHandler; ++ parser->m_processingInstructionHandler = oldProcessingInstructionHandler; ++ parser->m_commentHandler = oldCommentHandler; ++ parser->m_startCdataSectionHandler = oldStartCdataSectionHandler; ++ parser->m_endCdataSectionHandler = oldEndCdataSectionHandler; ++ parser->m_defaultHandler = oldDefaultHandler; ++ parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler; ++ parser->m_notationDeclHandler = oldNotationDeclHandler; ++ parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler; ++ parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler; ++ parser->m_notStandaloneHandler = oldNotStandaloneHandler; ++ parser->m_externalEntityRefHandler = oldExternalEntityRefHandler; ++ parser->m_skippedEntityHandler = oldSkippedEntityHandler; ++ parser->m_unknownEncodingHandler = oldUnknownEncodingHandler; ++ parser->m_elementDeclHandler = oldElementDeclHandler; ++ parser->m_attlistDeclHandler = oldAttlistDeclHandler; ++ parser->m_entityDeclHandler = oldEntityDeclHandler; ++ parser->m_xmlDeclHandler = oldXmlDeclHandler; ++ parser->m_declElementType = oldDeclElementType; ++ parser->m_userData = oldUserData; + if (oldUserData == oldHandlerArg) +- handlerArg = userData; ++ parser->m_handlerArg = parser->m_userData; + else +- handlerArg = parser; ++ parser->m_handlerArg = parser; + if (oldExternalEntityRefHandlerArg != oldParser) +- externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg; +- defaultExpandInternalEntities = oldDefaultExpandInternalEntities; +- ns_triplets = oldns_triplets; +- hash_secret_salt = oldhash_secret_salt; +- parentParser = oldParser; ++ parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg; ++ parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities; ++ parser->m_ns_triplets = oldns_triplets; ++ parser->m_hash_secret_salt = oldhash_secret_salt; ++ parser->m_parentParser = oldParser; + #ifdef XML_DTD +- paramEntityParsing = oldParamEntityParsing; +- prologState.inEntityValue = oldInEntityValue; ++ parser->m_paramEntityParsing = oldParamEntityParsing; ++ parser->m_prologState.inEntityValue = oldInEntityValue; + if (context) { + #endif /* XML_DTD */ +- if (!dtdCopy(oldParser, _dtd, oldDtd, &parser->m_mem) ++ if (!dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem) + || !setContext(parser, context)) { + XML_ParserFree(parser); + return NULL; + } +- processor = externalEntityInitProcessor; ++ parser->m_processor = externalEntityInitProcessor; + #ifdef XML_DTD + } + else { +- /* The DTD instance referenced by _dtd is shared between the document's ++ /* The DTD instance referenced by parser->m_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. ++ parser->m_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; ++ parser->m_isParamEntity = XML_TRUE; ++ XmlPrologStateInitExternalEntity(&parser->m_prologState); ++ parser->m_processor = externalParEntInitProcessor; + } + #endif /* XML_DTD */ + return parser; +@@ -1461,8 +1368,8 @@ destroyBindings(BINDING *bindings, XML_Parser parser) + if (!b) + break; + bindings = b->nextTagBinding; +- FREE(b->uri); +- FREE(b); ++ FREE(parser, b->uri); ++ FREE(parser, b); + } + } + +@@ -1473,70 +1380,70 @@ XML_ParserFree(XML_Parser parser) + OPEN_INTERNAL_ENTITY *entityList; + if (parser == NULL) + return; +- /* free tagStack and freeTagList */ +- tagList = tagStack; ++ /* free m_tagStack and m_freeTagList */ ++ tagList = parser->m_tagStack; + for (;;) { + TAG *p; + if (tagList == NULL) { +- if (freeTagList == NULL) ++ if (parser->m_freeTagList == NULL) + break; +- tagList = freeTagList; +- freeTagList = NULL; ++ tagList = parser->m_freeTagList; ++ parser->m_freeTagList = NULL; + } + p = tagList; + tagList = tagList->parent; +- FREE(p->buf); ++ FREE(parser, p->buf); + destroyBindings(p->bindings, parser); +- FREE(p); ++ FREE(parser, p); + } +- /* free openInternalEntities and freeInternalEntities */ +- entityList = openInternalEntities; ++ /* free m_openInternalEntities and m_freeInternalEntities */ ++ entityList = parser->m_openInternalEntities; + for (;;) { + OPEN_INTERNAL_ENTITY *openEntity; + if (entityList == NULL) { +- if (freeInternalEntities == NULL) ++ if (parser->m_freeInternalEntities == NULL) + break; +- entityList = freeInternalEntities; +- freeInternalEntities = NULL; ++ entityList = parser->m_freeInternalEntities; ++ parser->m_freeInternalEntities = NULL; + } + openEntity = entityList; + entityList = entityList->next; +- FREE(openEntity); ++ FREE(parser, openEntity); + } + +- destroyBindings(freeBindingList, parser); +- destroyBindings(inheritedBindings, parser); +- poolDestroy(&tempPool); +- poolDestroy(&temp2Pool); +- FREE((void *)protocolEncodingName); ++ destroyBindings(parser->m_freeBindingList, parser); ++ destroyBindings(parser->m_inheritedBindings, parser); ++ poolDestroy(&parser->m_tempPool); ++ poolDestroy(&parser->m_temp2Pool); ++ FREE(parser, (void *)parser->m_protocolEncodingName); + #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) ++ if (!parser->m_isParamEntity && parser->m_dtd) + #else +- if (_dtd) ++ if (parser->m_dtd) + #endif /* XML_DTD */ +- dtdDestroy(_dtd, (XML_Bool)!parentParser, &parser->m_mem); +- FREE((void *)atts); ++ dtdDestroy(parser->m_dtd, (XML_Bool)!parser->m_parentParser, &parser->m_mem); ++ FREE(parser, (void *)parser->m_atts); + #ifdef XML_ATTR_INFO +- FREE((void *)attInfo); ++ FREE(parser, (void *)parser->m_attInfo); + #endif +- FREE(groupConnector); +- FREE(buffer); +- FREE(dataBuf); +- FREE(nsAtts); +- FREE(unknownEncodingMem); +- if (unknownEncodingRelease) +- unknownEncodingRelease(unknownEncodingData); +- FREE(parser); ++ FREE(parser, parser->m_groupConnector); ++ FREE(parser, parser->m_buffer); ++ FREE(parser, parser->m_dataBuf); ++ FREE(parser, parser->m_nsAtts); ++ FREE(parser, parser->m_unknownEncodingMem); ++ if (parser->m_unknownEncodingRelease) ++ parser->m_unknownEncodingRelease(parser->m_unknownEncodingData); ++ FREE(parser, parser); + } + + void XMLCALL + XML_UseParserAsHandlerArg(XML_Parser parser) + { + if (parser != NULL) +- handlerArg = parser; ++ parser->m_handlerArg = parser; + } + + enum XML_Error XMLCALL +@@ -1546,9 +1453,9 @@ XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) + return XML_ERROR_INVALID_ARGUMENT; + #ifdef XML_DTD + /* block after XML_Parse()/XML_ParseBuffer() has been called */ +- if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED) ++ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING; +- useForeignDTD = useDTD; ++ parser->m_useForeignDTD = useDTD; + return XML_ERROR_NONE; + #else + return XML_ERROR_FEATURE_REQUIRES_XML_DTD; +@@ -1561,9 +1468,9 @@ XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) + if (parser == NULL) + return; + /* block after XML_Parse()/XML_ParseBuffer() has been called */ +- if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED) ++ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return; +- ns_triplets = do_nst ? XML_TRUE : XML_FALSE; ++ parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE; + } + + void XMLCALL +@@ -1571,10 +1478,10 @@ XML_SetUserData(XML_Parser parser, void *p) + { + if (parser == NULL) + return; +- if (handlerArg == userData) +- handlerArg = userData = p; ++ if (parser->m_handlerArg == parser->m_userData) ++ parser->m_handlerArg = parser->m_userData = p; + else +- userData = p; ++ parser->m_userData = p; + } + + enum XML_Status XMLCALL +@@ -1583,13 +1490,13 @@ XML_SetBase(XML_Parser parser, const XML_Char *p) + if (parser == NULL) + return XML_STATUS_ERROR; + if (p) { +- p = poolCopyString(&_dtd->pool, p); ++ p = poolCopyString(&parser->m_dtd->pool, p); + if (!p) + return XML_STATUS_ERROR; +- curBase = p; ++ parser->m_curBase = p; + } + else +- curBase = NULL; ++ parser->m_curBase = NULL; + return XML_STATUS_OK; + } + +@@ -1598,7 +1505,7 @@ XML_GetBase(XML_Parser parser) + { + if (parser == NULL) + return NULL; +- return curBase; ++ return parser->m_curBase; + } + + int XMLCALL +@@ -1606,7 +1513,7 @@ XML_GetSpecifiedAttributeCount(XML_Parser parser) + { + if (parser == NULL) + return -1; +- return nSpecifiedAtts; ++ return parser->m_nSpecifiedAtts; + } + + int XMLCALL +@@ -1614,7 +1521,7 @@ XML_GetIdAttributeIndex(XML_Parser parser) + { + if (parser == NULL) + return -1; +- return idAttIndex; ++ return parser->m_idAttIndex; + } + + #ifdef XML_ATTR_INFO +@@ -1623,7 +1530,7 @@ XML_GetAttributeInfo(XML_Parser parser) + { + if (parser == NULL) + return NULL; +- return attInfo; ++ return parser->m_attInfo; + } + #endif + +@@ -1634,22 +1541,22 @@ XML_SetElementHandler(XML_Parser parser, + { + if (parser == NULL) + return; +- startElementHandler = start; +- endElementHandler = end; ++ parser->m_startElementHandler = start; ++ parser->m_endElementHandler = end; + } + + void XMLCALL + XML_SetStartElementHandler(XML_Parser parser, + XML_StartElementHandler start) { + if (parser != NULL) +- startElementHandler = start; ++ parser->m_startElementHandler = start; + } + + void XMLCALL + XML_SetEndElementHandler(XML_Parser parser, + XML_EndElementHandler end) { + if (parser != NULL) +- endElementHandler = end; ++ parser->m_endElementHandler = end; + } + + void XMLCALL +@@ -1657,7 +1564,7 @@ XML_SetCharacterDataHandler(XML_Parser parser, + XML_CharacterDataHandler handler) + { + if (parser != NULL) +- characterDataHandler = handler; ++ parser->m_characterDataHandler = handler; + } + + void XMLCALL +@@ -1665,7 +1572,7 @@ XML_SetProcessingInstructionHandler(XML_Parser parser, + XML_ProcessingInstructionHandler handler) + { + if (parser != NULL) +- processingInstructionHandler = handler; ++ parser->m_processingInstructionHandler = handler; + } + + void XMLCALL +@@ -1673,7 +1580,7 @@ XML_SetCommentHandler(XML_Parser parser, + XML_CommentHandler handler) + { + if (parser != NULL) +- commentHandler = handler; ++ parser->m_commentHandler = handler; + } + + void XMLCALL +@@ -1683,22 +1590,22 @@ XML_SetCdataSectionHandler(XML_Parser parser, + { + if (parser == NULL) + return; +- startCdataSectionHandler = start; +- endCdataSectionHandler = end; ++ parser->m_startCdataSectionHandler = start; ++ parser->m_endCdataSectionHandler = end; + } + + void XMLCALL + XML_SetStartCdataSectionHandler(XML_Parser parser, + XML_StartCdataSectionHandler start) { + if (parser != NULL) +- startCdataSectionHandler = start; ++ parser->m_startCdataSectionHandler = start; + } + + void XMLCALL + XML_SetEndCdataSectionHandler(XML_Parser parser, + XML_EndCdataSectionHandler end) { + if (parser != NULL) +- endCdataSectionHandler = end; ++ parser->m_endCdataSectionHandler = end; + } + + void XMLCALL +@@ -1707,8 +1614,8 @@ XML_SetDefaultHandler(XML_Parser parser, + { + if (parser == NULL) + return; +- defaultHandler = handler; +- defaultExpandInternalEntities = XML_FALSE; ++ parser->m_defaultHandler = handler; ++ parser->m_defaultExpandInternalEntities = XML_FALSE; + } + + void XMLCALL +@@ -1717,8 +1624,8 @@ XML_SetDefaultHandlerExpand(XML_Parser parser, + { + if (parser == NULL) + return; +- defaultHandler = handler; +- defaultExpandInternalEntities = XML_TRUE; ++ parser->m_defaultHandler = handler; ++ parser->m_defaultExpandInternalEntities = XML_TRUE; + } + + void XMLCALL +@@ -1728,22 +1635,22 @@ XML_SetDoctypeDeclHandler(XML_Parser parser, + { + if (parser == NULL) + return; +- startDoctypeDeclHandler = start; +- endDoctypeDeclHandler = end; ++ parser->m_startDoctypeDeclHandler = start; ++ parser->m_endDoctypeDeclHandler = end; + } + + void XMLCALL + XML_SetStartDoctypeDeclHandler(XML_Parser parser, + XML_StartDoctypeDeclHandler start) { + if (parser != NULL) +- startDoctypeDeclHandler = start; ++ parser->m_startDoctypeDeclHandler = start; + } + + void XMLCALL + XML_SetEndDoctypeDeclHandler(XML_Parser parser, + XML_EndDoctypeDeclHandler end) { + if (parser != NULL) +- endDoctypeDeclHandler = end; ++ parser->m_endDoctypeDeclHandler = end; + } + + void XMLCALL +@@ -1751,7 +1658,7 @@ XML_SetUnparsedEntityDeclHandler(XML_Parser parser, + XML_UnparsedEntityDeclHandler handler) + { + if (parser != NULL) +- unparsedEntityDeclHandler = handler; ++ parser->m_unparsedEntityDeclHandler = handler; + } + + void XMLCALL +@@ -1759,7 +1666,7 @@ XML_SetNotationDeclHandler(XML_Parser parser, + XML_NotationDeclHandler handler) + { + if (parser != NULL) +- notationDeclHandler = handler; ++ parser->m_notationDeclHandler = handler; + } + + void XMLCALL +@@ -1769,22 +1676,22 @@ XML_SetNamespaceDeclHandler(XML_Parser parser, + { + if (parser == NULL) + return; +- startNamespaceDeclHandler = start; +- endNamespaceDeclHandler = end; ++ parser->m_startNamespaceDeclHandler = start; ++ parser->m_endNamespaceDeclHandler = end; + } + + void XMLCALL + XML_SetStartNamespaceDeclHandler(XML_Parser parser, + XML_StartNamespaceDeclHandler start) { + if (parser != NULL) +- startNamespaceDeclHandler = start; ++ parser->m_startNamespaceDeclHandler = start; + } + + void XMLCALL + XML_SetEndNamespaceDeclHandler(XML_Parser parser, + XML_EndNamespaceDeclHandler end) { + if (parser != NULL) +- endNamespaceDeclHandler = end; ++ parser->m_endNamespaceDeclHandler = end; + } + + void XMLCALL +@@ -1792,7 +1699,7 @@ XML_SetNotStandaloneHandler(XML_Parser parser, + XML_NotStandaloneHandler handler) + { + if (parser != NULL) +- notStandaloneHandler = handler; ++ parser->m_notStandaloneHandler = handler; + } + + void XMLCALL +@@ -1800,7 +1707,7 @@ XML_SetExternalEntityRefHandler(XML_Parser parser, + XML_ExternalEntityRefHandler handler) + { + if (parser != NULL) +- externalEntityRefHandler = handler; ++ parser->m_externalEntityRefHandler = handler; + } + + void XMLCALL +@@ -1809,9 +1716,9 @@ XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) + if (parser == NULL) + return; + if (arg) +- externalEntityRefHandlerArg = (XML_Parser)arg; ++ parser->m_externalEntityRefHandlerArg = (XML_Parser)arg; + else +- externalEntityRefHandlerArg = parser; ++ parser->m_externalEntityRefHandlerArg = parser; + } + + void XMLCALL +@@ -1819,7 +1726,7 @@ XML_SetSkippedEntityHandler(XML_Parser parser, + XML_SkippedEntityHandler handler) + { + if (parser != NULL) +- skippedEntityHandler = handler; ++ parser->m_skippedEntityHandler = handler; + } + + void XMLCALL +@@ -1829,8 +1736,8 @@ XML_SetUnknownEncodingHandler(XML_Parser parser, + { + if (parser == NULL) + return; +- unknownEncodingHandler = handler; +- unknownEncodingHandlerData = data; ++ parser->m_unknownEncodingHandler = handler; ++ parser->m_unknownEncodingHandlerData = data; + } + + void XMLCALL +@@ -1838,7 +1745,7 @@ XML_SetElementDeclHandler(XML_Parser parser, + XML_ElementDeclHandler eldecl) + { + if (parser != NULL) +- elementDeclHandler = eldecl; ++ parser->m_elementDeclHandler = eldecl; + } + + void XMLCALL +@@ -1846,7 +1753,7 @@ XML_SetAttlistDeclHandler(XML_Parser parser, + XML_AttlistDeclHandler attdecl) + { + if (parser != NULL) +- attlistDeclHandler = attdecl; ++ parser->m_attlistDeclHandler = attdecl; + } + + void XMLCALL +@@ -1854,14 +1761,14 @@ XML_SetEntityDeclHandler(XML_Parser parser, + XML_EntityDeclHandler handler) + { + if (parser != NULL) +- entityDeclHandler = handler; ++ parser->m_entityDeclHandler = handler; + } + + void XMLCALL + XML_SetXmlDeclHandler(XML_Parser parser, + XML_XmlDeclHandler handler) { + if (parser != NULL) +- xmlDeclHandler = handler; ++ parser->m_xmlDeclHandler = handler; + } + + int XMLCALL +@@ -1871,10 +1778,10 @@ XML_SetParamEntityParsing(XML_Parser parser, + if (parser == NULL) + return 0; + /* block after XML_Parse()/XML_ParseBuffer() has been called */ +- if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED) ++ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return 0; + #ifdef XML_DTD +- paramEntityParsing = peParsing; ++ parser->m_paramEntityParsing = peParsing; + return 1; + #else + return peParsing == XML_PARAM_ENTITY_PARSING_NEVER; +@@ -1890,9 +1797,9 @@ XML_SetHashSalt(XML_Parser parser, + if (parser->m_parentParser) + return XML_SetHashSalt(parser->m_parentParser, hash_salt); + /* block after XML_Parse()/XML_ParseBuffer() has been called */ +- if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED) ++ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return 0; +- hash_secret_salt = hash_salt; ++ parser->m_hash_secret_salt = hash_salt; + return 1; + } + +@@ -1904,37 +1811,38 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) + parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT; + return XML_STATUS_ERROR; + } +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: +- errorCode = XML_ERROR_SUSPENDED; ++ parser->m_errorCode = XML_ERROR_SUSPENDED; + return XML_STATUS_ERROR; + case XML_FINISHED: +- errorCode = XML_ERROR_FINISHED; ++ parser->m_errorCode = XML_ERROR_FINISHED; + return XML_STATUS_ERROR; + case XML_INITIALIZED: +- if (parentParser == NULL && !startParsing(parser)) { +- errorCode = XML_ERROR_NO_MEMORY; ++ if (parser->m_parentParser == NULL && !startParsing(parser)) { ++ parser->m_errorCode = XML_ERROR_NO_MEMORY; + return XML_STATUS_ERROR; + } ++ /* fall through */ + default: +- ps_parsing = XML_PARSING; ++ parser->m_parsingStatus.parsing = XML_PARSING; + } + + if (len == 0) { +- ps_finalBuffer = (XML_Bool)isFinal; ++ parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + if (!isFinal) + return XML_STATUS_OK; +- positionPtr = bufferPtr; +- parseEndPtr = bufferEnd; ++ parser->m_positionPtr = parser->m_bufferPtr; ++ parser->m_parseEndPtr = parser->m_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); ++ parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr); + +- if (errorCode == XML_ERROR_NONE) { +- switch (ps_parsing) { ++ if (parser->m_errorCode == XML_ERROR_NONE) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + /* It is hard to be certain, but it seems that this case + * cannot occur. This code is cleaning up a previous parse +@@ -1948,54 +1856,54 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) + * + * LCOV_EXCL_START + */ +- XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position); +- positionPtr = bufferPtr; ++ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position); ++ parser->m_positionPtr = parser->m_bufferPtr; + return XML_STATUS_SUSPENDED; + /* LCOV_EXCL_STOP */ + case XML_INITIALIZED: + case XML_PARSING: +- ps_parsing = XML_FINISHED; ++ parser->m_parsingStatus.parsing = XML_FINISHED; + /* fall through */ + default: + return XML_STATUS_OK; + } + } +- eventEndPtr = eventPtr; +- processor = errorProcessor; ++ parser->m_eventEndPtr = parser->m_eventPtr; ++ parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + #ifndef XML_CONTEXT_BYTES +- else if (bufferPtr == bufferEnd) { ++ else if (parser->m_bufferPtr == parser->m_bufferEnd) { + const char *end; + int nLeftOver; + enum XML_Status result; + /* Detect overflow (a+b > MAX <==> b > MAX-a) */ +- if (len > ((XML_Size)-1) / 2 - parseEndByteIndex) { +- errorCode = XML_ERROR_NO_MEMORY; +- eventPtr = eventEndPtr = NULL; +- processor = errorProcessor; ++ if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) { ++ parser->m_errorCode = XML_ERROR_NO_MEMORY; ++ parser->m_eventPtr = parser->m_eventEndPtr = NULL; ++ parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } +- parseEndByteIndex += len; +- positionPtr = s; +- ps_finalBuffer = (XML_Bool)isFinal; ++ parser->m_parseEndByteIndex += len; ++ parser->m_positionPtr = s; ++ parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + +- errorCode = processor(parser, s, parseEndPtr = s + len, &end); ++ parser->m_errorCode = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end); + +- if (errorCode != XML_ERROR_NONE) { +- eventEndPtr = eventPtr; +- processor = errorProcessor; ++ if (parser->m_errorCode != XML_ERROR_NONE) { ++ parser->m_eventEndPtr = parser->m_eventPtr; ++ parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + else { +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + result = XML_STATUS_SUSPENDED; + break; + case XML_INITIALIZED: + case XML_PARSING: + if (isFinal) { +- ps_parsing = XML_FINISHED; ++ parser->m_parsingStatus.parsing = XML_FINISHED; + return XML_STATUS_OK; + } + /* fall through */ +@@ -2004,35 +1912,33 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) + } + } + +- XmlUpdatePosition(encoding, positionPtr, end, &position); ++ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end, &parser->m_position); + nLeftOver = s + len - end; + if (nLeftOver) { +- if (buffer == NULL || nLeftOver > bufferLim - buffer) { ++ if (parser->m_buffer == NULL || nLeftOver > parser->m_bufferLim - parser->m_buffer) { + /* avoid _signed_ integer overflow */ + char *temp = NULL; + const int bytesToAllocate = (int)((unsigned)len * 2U); + if (bytesToAllocate > 0) { +- temp = (buffer == NULL +- ? (char *)MALLOC(bytesToAllocate) +- : (char *)REALLOC(buffer, bytesToAllocate)); ++ temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate); + } + if (temp == NULL) { +- errorCode = XML_ERROR_NO_MEMORY; +- eventPtr = eventEndPtr = NULL; +- processor = errorProcessor; ++ parser->m_errorCode = XML_ERROR_NO_MEMORY; ++ parser->m_eventPtr = parser->m_eventEndPtr = NULL; ++ parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } +- buffer = temp; +- bufferLim = buffer + bytesToAllocate; ++ parser->m_buffer = temp; ++ parser->m_bufferLim = parser->m_buffer + bytesToAllocate; + } +- memcpy(buffer, end, nLeftOver); ++ memcpy(parser->m_buffer, end, nLeftOver); + } +- bufferPtr = buffer; +- bufferEnd = buffer + nLeftOver; +- positionPtr = bufferPtr; +- parseEndPtr = bufferEnd; +- eventPtr = bufferPtr; +- eventEndPtr = bufferPtr; ++ parser->m_bufferPtr = parser->m_buffer; ++ parser->m_bufferEnd = parser->m_buffer + nLeftOver; ++ parser->m_positionPtr = parser->m_bufferPtr; ++ parser->m_parseEndPtr = parser->m_bufferEnd; ++ parser->m_eventPtr = parser->m_bufferPtr; ++ parser->m_eventEndPtr = parser->m_bufferPtr; + return result; + } + #endif /* not defined XML_CONTEXT_BYTES */ +@@ -2055,53 +1961,54 @@ XML_ParseBuffer(XML_Parser parser, int len, int isFinal) + + if (parser == NULL) + return XML_STATUS_ERROR; +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: +- errorCode = XML_ERROR_SUSPENDED; ++ parser->m_errorCode = XML_ERROR_SUSPENDED; + return XML_STATUS_ERROR; + case XML_FINISHED: +- errorCode = XML_ERROR_FINISHED; ++ parser->m_errorCode = XML_ERROR_FINISHED; + return XML_STATUS_ERROR; + case XML_INITIALIZED: +- if (parentParser == NULL && !startParsing(parser)) { +- errorCode = XML_ERROR_NO_MEMORY; ++ if (parser->m_parentParser == NULL && !startParsing(parser)) { ++ parser->m_errorCode = XML_ERROR_NO_MEMORY; + return XML_STATUS_ERROR; + } ++ /* fall through */ + default: +- ps_parsing = XML_PARSING; ++ parser->m_parsingStatus.parsing = XML_PARSING; + } + +- start = bufferPtr; +- positionPtr = start; +- bufferEnd += len; +- parseEndPtr = bufferEnd; +- parseEndByteIndex += len; +- ps_finalBuffer = (XML_Bool)isFinal; ++ start = parser->m_bufferPtr; ++ parser->m_positionPtr = start; ++ parser->m_bufferEnd += len; ++ parser->m_parseEndPtr = parser->m_bufferEnd; ++ parser->m_parseEndByteIndex += len; ++ parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + +- errorCode = processor(parser, start, parseEndPtr, &bufferPtr); ++ parser->m_errorCode = parser->m_processor(parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr); + +- if (errorCode != XML_ERROR_NONE) { +- eventEndPtr = eventPtr; +- processor = errorProcessor; ++ if (parser->m_errorCode != XML_ERROR_NONE) { ++ parser->m_eventEndPtr = parser->m_eventPtr; ++ parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + else { +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + result = XML_STATUS_SUSPENDED; + break; + case XML_INITIALIZED: + case XML_PARSING: + if (isFinal) { +- ps_parsing = XML_FINISHED; ++ parser->m_parsingStatus.parsing = XML_FINISHED; + return result; + } + default: ; /* should not happen */ + } + } + +- XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position); +- positionPtr = bufferPtr; ++ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position); ++ parser->m_positionPtr = parser->m_bufferPtr; + return result; + } + +@@ -2111,52 +2018,59 @@ XML_GetBuffer(XML_Parser parser, int len) + if (parser == NULL) + return NULL; + if (len < 0) { +- errorCode = XML_ERROR_NO_MEMORY; ++ parser->m_errorCode = XML_ERROR_NO_MEMORY; + return NULL; + } +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: +- errorCode = XML_ERROR_SUSPENDED; ++ parser->m_errorCode = XML_ERROR_SUSPENDED; + return NULL; + case XML_FINISHED: +- errorCode = XML_ERROR_FINISHED; ++ parser->m_errorCode = XML_ERROR_FINISHED; + return NULL; + default: ; + } + +- if (len > bufferLim - bufferEnd) { ++ if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)) { + #ifdef XML_CONTEXT_BYTES + int keep; + #endif /* defined XML_CONTEXT_BYTES */ + /* Do not invoke signed arithmetic overflow: */ +- int neededSize = (int) ((unsigned)len + (unsigned)(bufferEnd - bufferPtr)); ++ int neededSize = (int) ((unsigned)len + ++ (unsigned)EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, ++ parser->m_bufferPtr)); + if (neededSize < 0) { +- errorCode = XML_ERROR_NO_MEMORY; ++ parser->m_errorCode = XML_ERROR_NO_MEMORY; + return NULL; + } + #ifdef XML_CONTEXT_BYTES +- keep = (int)(bufferPtr - buffer); ++ keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer); + if (keep > XML_CONTEXT_BYTES) + keep = XML_CONTEXT_BYTES; + neededSize += keep; + #endif /* defined XML_CONTEXT_BYTES */ +- if (neededSize <= bufferLim - buffer) { ++ if (neededSize <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_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; ++ if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) { ++ int offset = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer) - keep; ++ /* The buffer pointers cannot be NULL here; we have at least some bytes in the buffer */ ++ memmove(parser->m_buffer, &parser->m_buffer[offset], parser->m_bufferEnd - parser->m_bufferPtr + keep); ++ parser->m_bufferEnd -= offset; ++ parser->m_bufferPtr -= offset; + } + #else +- memmove(buffer, bufferPtr, bufferEnd - bufferPtr); +- bufferEnd = buffer + (bufferEnd - bufferPtr); +- bufferPtr = buffer; ++ if (parser->m_buffer && parser->m_bufferPtr) { ++ memmove(parser->m_buffer, parser->m_bufferPtr, ++ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)); ++ parser->m_bufferEnd = parser->m_buffer + ++ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr); ++ parser->m_bufferPtr = parser->m_buffer; ++ } + #endif /* not defined XML_CONTEXT_BYTES */ + } + else { + char *newBuf; +- int bufferSize = (int)(bufferLim - bufferPtr); ++ int bufferSize = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferPtr); + if (bufferSize == 0) + bufferSize = INIT_BUFFER_SIZE; + do { +@@ -2164,43 +2078,52 @@ XML_GetBuffer(XML_Parser parser, int len) + bufferSize = (int) (2U * (unsigned) bufferSize); + } while (bufferSize < neededSize && bufferSize > 0); + if (bufferSize <= 0) { +- errorCode = XML_ERROR_NO_MEMORY; ++ parser->m_errorCode = XML_ERROR_NO_MEMORY; + return NULL; + } +- newBuf = (char *)MALLOC(bufferSize); ++ newBuf = (char *)MALLOC(parser, bufferSize); + if (newBuf == 0) { +- errorCode = XML_ERROR_NO_MEMORY; ++ parser->m_errorCode = XML_ERROR_NO_MEMORY; + return NULL; + } +- bufferLim = newBuf + bufferSize; ++ parser->m_bufferLim = newBuf + bufferSize; + #ifdef XML_CONTEXT_BYTES +- if (bufferPtr) { +- int keep = (int)(bufferPtr - buffer); ++ if (parser->m_bufferPtr) { ++ int keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_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; ++ memcpy(newBuf, &parser->m_bufferPtr[-keep], ++ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep); ++ FREE(parser, parser->m_buffer); ++ parser->m_buffer = newBuf; ++ parser->m_bufferEnd = parser->m_buffer + ++ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep; ++ parser->m_bufferPtr = parser->m_buffer + keep; + } + else { +- bufferEnd = newBuf + (bufferEnd - bufferPtr); +- bufferPtr = buffer = newBuf; ++ /* This must be a brand new buffer with no data in it yet */ ++ parser->m_bufferEnd = newBuf; ++ parser->m_bufferPtr = parser->m_buffer = newBuf; + } + #else +- if (bufferPtr) { +- memcpy(newBuf, bufferPtr, bufferEnd - bufferPtr); +- FREE(buffer); ++ if (parser->m_bufferPtr) { ++ memcpy(newBuf, parser->m_bufferPtr, ++ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)); ++ FREE(parser, parser->m_buffer); ++ parser->m_bufferEnd = newBuf + ++ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr); ++ } ++ else { ++ /* This must be a brand new buffer with no data in it yet */ ++ parser->m_bufferEnd = newBuf; + } +- bufferEnd = newBuf + (bufferEnd - bufferPtr); +- bufferPtr = buffer = newBuf; ++ parser->m_bufferPtr = parser->m_buffer = newBuf; + #endif /* not defined XML_CONTEXT_BYTES */ + } +- eventPtr = eventEndPtr = NULL; +- positionPtr = NULL; ++ parser->m_eventPtr = parser->m_eventEndPtr = NULL; ++ parser->m_positionPtr = NULL; + } +- return bufferEnd; ++ return parser->m_bufferEnd; + } + + enum XML_Status XMLCALL +@@ -2208,29 +2131,29 @@ XML_StopParser(XML_Parser parser, XML_Bool resumable) + { + if (parser == NULL) + return XML_STATUS_ERROR; +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + if (resumable) { +- errorCode = XML_ERROR_SUSPENDED; ++ parser->m_errorCode = XML_ERROR_SUSPENDED; + return XML_STATUS_ERROR; + } +- ps_parsing = XML_FINISHED; ++ parser->m_parsingStatus.parsing = XML_FINISHED; + break; + case XML_FINISHED: +- errorCode = XML_ERROR_FINISHED; ++ parser->m_errorCode = XML_ERROR_FINISHED; + return XML_STATUS_ERROR; + default: + if (resumable) { + #ifdef XML_DTD +- if (isParamEntity) { +- errorCode = XML_ERROR_SUSPEND_PE; ++ if (parser->m_isParamEntity) { ++ parser->m_errorCode = XML_ERROR_SUSPEND_PE; + return XML_STATUS_ERROR; + } + #endif +- ps_parsing = XML_SUSPENDED; ++ parser->m_parsingStatus.parsing = XML_SUSPENDED; + } + else +- ps_parsing = XML_FINISHED; ++ parser->m_parsingStatus.parsing = XML_FINISHED; + } + return XML_STATUS_OK; + } +@@ -2242,36 +2165,36 @@ XML_ResumeParser(XML_Parser parser) + + if (parser == NULL) + return XML_STATUS_ERROR; +- if (ps_parsing != XML_SUSPENDED) { +- errorCode = XML_ERROR_NOT_SUSPENDED; ++ if (parser->m_parsingStatus.parsing != XML_SUSPENDED) { ++ parser->m_errorCode = XML_ERROR_NOT_SUSPENDED; + return XML_STATUS_ERROR; + } +- ps_parsing = XML_PARSING; ++ parser->m_parsingStatus.parsing = XML_PARSING; + +- errorCode = processor(parser, bufferPtr, parseEndPtr, &bufferPtr); ++ parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr); + +- if (errorCode != XML_ERROR_NONE) { +- eventEndPtr = eventPtr; +- processor = errorProcessor; ++ if (parser->m_errorCode != XML_ERROR_NONE) { ++ parser->m_eventEndPtr = parser->m_eventPtr; ++ parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + else { +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + result = XML_STATUS_SUSPENDED; + break; + case XML_INITIALIZED: + case XML_PARSING: +- if (ps_finalBuffer) { +- ps_parsing = XML_FINISHED; ++ if (parser->m_parsingStatus.finalBuffer) { ++ parser->m_parsingStatus.parsing = XML_FINISHED; + return result; + } + default: ; + } + } + +- XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position); +- positionPtr = bufferPtr; ++ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position); ++ parser->m_positionPtr = parser->m_bufferPtr; + return result; + } + +@@ -2289,7 +2212,7 @@ XML_GetErrorCode(XML_Parser parser) + { + if (parser == NULL) + return XML_ERROR_INVALID_ARGUMENT; +- return errorCode; ++ return parser->m_errorCode; + } + + XML_Index XMLCALL +@@ -2297,8 +2220,8 @@ XML_GetCurrentByteIndex(XML_Parser parser) + { + if (parser == NULL) + return -1; +- if (eventPtr) +- return (XML_Index)(parseEndByteIndex - (parseEndPtr - eventPtr)); ++ if (parser->m_eventPtr) ++ return (XML_Index)(parser->m_parseEndByteIndex - (parser->m_parseEndPtr - parser->m_eventPtr)); + return -1; + } + +@@ -2307,8 +2230,8 @@ XML_GetCurrentByteCount(XML_Parser parser) + { + if (parser == NULL) + return 0; +- if (eventEndPtr && eventPtr) +- return (int)(eventEndPtr - eventPtr); ++ if (parser->m_eventEndPtr && parser->m_eventPtr) ++ return (int)(parser->m_eventEndPtr - parser->m_eventPtr); + return 0; + } + +@@ -2318,12 +2241,12 @@ XML_GetInputContext(XML_Parser parser, int *offset, int *size) + #ifdef XML_CONTEXT_BYTES + if (parser == NULL) + return NULL; +- if (eventPtr && buffer) { ++ if (parser->m_eventPtr && parser->m_buffer) { + if (offset != NULL) +- *offset = (int)(eventPtr - buffer); ++ *offset = (int)(parser->m_eventPtr - parser->m_buffer); + if (size != NULL) +- *size = (int)(bufferEnd - buffer); +- return buffer; ++ *size = (int)(parser->m_bufferEnd - parser->m_buffer); ++ return parser->m_buffer; + } + #else + (void)parser; +@@ -2338,11 +2261,11 @@ XML_GetCurrentLineNumber(XML_Parser parser) + { + if (parser == NULL) + return 0; +- if (eventPtr && eventPtr >= positionPtr) { +- XmlUpdatePosition(encoding, positionPtr, eventPtr, &position); +- positionPtr = eventPtr; ++ if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) { ++ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position); ++ parser->m_positionPtr = parser->m_eventPtr; + } +- return position.lineNumber + 1; ++ return parser->m_position.lineNumber + 1; + } + + XML_Size XMLCALL +@@ -2350,18 +2273,18 @@ XML_GetCurrentColumnNumber(XML_Parser parser) + { + if (parser == NULL) + return 0; +- if (eventPtr && eventPtr >= positionPtr) { +- XmlUpdatePosition(encoding, positionPtr, eventPtr, &position); +- positionPtr = eventPtr; ++ if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) { ++ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position); ++ parser->m_positionPtr = parser->m_eventPtr; + } +- return position.columnNumber; ++ return parser->m_position.columnNumber; + } + + void XMLCALL + XML_FreeContentModel(XML_Parser parser, XML_Content *model) + { + if (parser != NULL) +- FREE(model); ++ FREE(parser, model); + } + + void * XMLCALL +@@ -2369,7 +2292,7 @@ XML_MemMalloc(XML_Parser parser, size_t size) + { + if (parser == NULL) + return NULL; +- return MALLOC(size); ++ return MALLOC(parser, size); + } + + void * XMLCALL +@@ -2377,14 +2300,14 @@ XML_MemRealloc(XML_Parser parser, void *ptr, size_t size) + { + if (parser == NULL) + return NULL; +- return REALLOC(ptr, size); ++ return REALLOC(parser, ptr, size); + } + + void XMLCALL + XML_MemFree(XML_Parser parser, void *ptr) + { + if (parser != NULL) +- FREE(ptr); ++ FREE(parser, ptr); + } + + void XMLCALL +@@ -2392,65 +2315,110 @@ XML_DefaultCurrent(XML_Parser parser) + { + if (parser == NULL) + return; +- if (defaultHandler) { +- if (openInternalEntities) ++ if (parser->m_defaultHandler) { ++ if (parser->m_openInternalEntities) + reportDefault(parser, +- internalEncoding, +- openInternalEntities->internalEventPtr, +- openInternalEntities->internalEventEndPtr); ++ parser->m_internalEncoding, ++ parser->m_openInternalEntities->internalEventPtr, ++ parser->m_openInternalEntities->internalEventEndPtr); + else +- reportDefault(parser, encoding, eventPtr, eventEndPtr); ++ reportDefault(parser, parser->m_encoding, parser->m_eventPtr, parser->m_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]; ++ switch (code) { ++ case XML_ERROR_NONE: ++ return NULL; ++ case XML_ERROR_NO_MEMORY: ++ return XML_L("out of memory"); ++ case XML_ERROR_SYNTAX: ++ return XML_L("syntax error"); ++ case XML_ERROR_NO_ELEMENTS: ++ return XML_L("no element found"); ++ case XML_ERROR_INVALID_TOKEN: ++ return XML_L("not well-formed (invalid token)"); ++ case XML_ERROR_UNCLOSED_TOKEN: ++ return XML_L("unclosed token"); ++ case XML_ERROR_PARTIAL_CHAR: ++ return XML_L("partial character"); ++ case XML_ERROR_TAG_MISMATCH: ++ return XML_L("mismatched tag"); ++ case XML_ERROR_DUPLICATE_ATTRIBUTE: ++ return XML_L("duplicate attribute"); ++ case XML_ERROR_JUNK_AFTER_DOC_ELEMENT: ++ return XML_L("junk after document element"); ++ case XML_ERROR_PARAM_ENTITY_REF: ++ return XML_L("illegal parameter entity reference"); ++ case XML_ERROR_UNDEFINED_ENTITY: ++ return XML_L("undefined entity"); ++ case XML_ERROR_RECURSIVE_ENTITY_REF: ++ return XML_L("recursive entity reference"); ++ case XML_ERROR_ASYNC_ENTITY: ++ return XML_L("asynchronous entity"); ++ case XML_ERROR_BAD_CHAR_REF: ++ return XML_L("reference to invalid character number"); ++ case XML_ERROR_BINARY_ENTITY_REF: ++ return XML_L("reference to binary entity"); ++ case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: ++ return XML_L("reference to external entity in attribute"); ++ case XML_ERROR_MISPLACED_XML_PI: ++ return XML_L("XML or text declaration not at start of entity"); ++ case XML_ERROR_UNKNOWN_ENCODING: ++ return XML_L("unknown encoding"); ++ case XML_ERROR_INCORRECT_ENCODING: ++ return XML_L("encoding specified in XML declaration is incorrect"); ++ case XML_ERROR_UNCLOSED_CDATA_SECTION: ++ return XML_L("unclosed CDATA section"); ++ case XML_ERROR_EXTERNAL_ENTITY_HANDLING: ++ return XML_L("error in processing external entity reference"); ++ case XML_ERROR_NOT_STANDALONE: ++ return XML_L("document is not standalone"); ++ case XML_ERROR_UNEXPECTED_STATE: ++ return XML_L("unexpected parser state - please send a bug report"); ++ case XML_ERROR_ENTITY_DECLARED_IN_PE: ++ return XML_L("entity declared in parameter entity"); ++ case XML_ERROR_FEATURE_REQUIRES_XML_DTD: ++ return XML_L("requested feature requires XML_DTD support in Expat"); ++ case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING: ++ return XML_L("cannot change setting once parsing has begun"); ++ /* Added in 1.95.7. */ ++ case XML_ERROR_UNBOUND_PREFIX: ++ return XML_L("unbound prefix"); ++ /* Added in 1.95.8. */ ++ case XML_ERROR_UNDECLARING_PREFIX: ++ return XML_L("must not undeclare prefix"); ++ case XML_ERROR_INCOMPLETE_PE: ++ return XML_L("incomplete markup in parameter entity"); ++ case XML_ERROR_XML_DECL: ++ return XML_L("XML declaration not well-formed"); ++ case XML_ERROR_TEXT_DECL: ++ return XML_L("text declaration not well-formed"); ++ case XML_ERROR_PUBLICID: ++ return XML_L("illegal character(s) in public id"); ++ case XML_ERROR_SUSPENDED: ++ return XML_L("parser suspended"); ++ case XML_ERROR_NOT_SUSPENDED: ++ return XML_L("parser not suspended"); ++ case XML_ERROR_ABORTED: ++ return XML_L("parsing aborted"); ++ case XML_ERROR_FINISHED: ++ return XML_L("parsing finished"); ++ case XML_ERROR_SUSPEND_PE: ++ return XML_L("cannot suspend in external parameter entity"); ++ /* Added in 2.0.0. */ ++ case XML_ERROR_RESERVED_PREFIX_XML: ++ return XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name"); ++ case XML_ERROR_RESERVED_PREFIX_XMLNS: ++ return XML_L("reserved prefix (xmlns) must not be declared or undeclared"); ++ case XML_ERROR_RESERVED_NAMESPACE_URI: ++ return XML_L("prefix must not be bound to one of the reserved namespace names"); ++ /* Added in 2.2.5. */ ++ case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */ ++ return XML_L("invalid argument"); ++ } + return NULL; + } + +@@ -2533,12 +2501,12 @@ XML_GetFeatureList(void) + static XML_Bool + storeRawNames(XML_Parser parser) + { +- TAG *tag = tagStack; ++ TAG *tag = parser->m_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 ++ /* Stop if already stored. Since m_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. +@@ -2550,7 +2518,7 @@ storeRawNames(XML_Parser parser) + */ + bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char)); + if (bufSize > tag->bufEnd - tag->buf) { +- char *temp = (char *)REALLOC(tag->buf, bufSize); ++ char *temp = (char *)REALLOC(parser, tag->buf, bufSize); + if (temp == NULL) + return XML_FALSE; + /* if tag->name.str points to tag->buf (only when namespace +@@ -2581,8 +2549,8 @@ contentProcessor(XML_Parser parser, + const char *end, + const char **endPtr) + { +- enum XML_Error result = doContent(parser, 0, encoding, start, end, +- endPtr, (XML_Bool)!ps_finalBuffer); ++ enum XML_Error result = doContent(parser, 0, parser->m_encoding, start, end, ++ endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + if (result == XML_ERROR_NONE) { + if (!storeRawNames(parser)) + return XML_ERROR_NO_MEMORY; +@@ -2599,7 +2567,7 @@ externalEntityInitProcessor(XML_Parser parser, + enum XML_Error result = initializeEncoding(parser); + if (result != XML_ERROR_NONE) + return result; +- processor = externalEntityInitProcessor2; ++ parser->m_processor = externalEntityInitProcessor2; + return externalEntityInitProcessor2(parser, start, end, endPtr); + } + +@@ -2610,7 +2578,7 @@ externalEntityInitProcessor2(XML_Parser parser, + const char **endPtr) + { + const char *next = start; /* XmlContentTok doesn't always set the last arg */ +- int tok = XmlContentTok(encoding, start, end, &next); ++ int tok = XmlContentTok(parser->m_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, +@@ -2618,28 +2586,28 @@ externalEntityInitProcessor2(XML_Parser parser, + 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) { ++ if (next == end && !parser->m_parsingStatus.finalBuffer) { + *endPtr = next; + return XML_ERROR_NONE; + } + start = next; + break; + case XML_TOK_PARTIAL: +- if (!ps_finalBuffer) { ++ if (!parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + return XML_ERROR_NONE; + } +- eventPtr = start; ++ parser->m_eventPtr = start; + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: +- if (!ps_finalBuffer) { ++ if (!parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + return XML_ERROR_NONE; + } +- eventPtr = start; ++ parser->m_eventPtr = start; + return XML_ERROR_PARTIAL_CHAR; + } +- processor = externalEntityInitProcessor3; ++ parser->m_processor = externalEntityInitProcessor3; + return externalEntityInitProcessor3(parser, start, end, endPtr); + } + +@@ -2651,9 +2619,9 @@ externalEntityInitProcessor3(XML_Parser parser, + { + int tok; + const char *next = start; /* XmlContentTok doesn't always set the last arg */ +- eventPtr = start; +- tok = XmlContentTok(encoding, start, end, &next); +- eventEndPtr = next; ++ parser->m_eventPtr = start; ++ tok = XmlContentTok(parser->m_encoding, start, end, &next); ++ parser->m_eventEndPtr = next; + + switch (tok) { + case XML_TOK_XML_DECL: +@@ -2662,7 +2630,7 @@ externalEntityInitProcessor3(XML_Parser parser, + result = processXmlDecl(parser, 1, start, next); + if (result != XML_ERROR_NONE) + return result; +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *endPtr = next; + return XML_ERROR_NONE; +@@ -2674,20 +2642,20 @@ externalEntityInitProcessor3(XML_Parser parser, + } + break; + case XML_TOK_PARTIAL: +- if (!ps_finalBuffer) { ++ if (!parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + return XML_ERROR_NONE; + } + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: +- if (!ps_finalBuffer) { ++ if (!parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + } +- processor = externalEntityContentProcessor; +- tagLevel = 1; ++ parser->m_processor = externalEntityContentProcessor; ++ parser->m_tagLevel = 1; + return externalEntityContentProcessor(parser, start, end, endPtr); + } + +@@ -2697,8 +2665,8 @@ externalEntityContentProcessor(XML_Parser parser, + const char *end, + const char **endPtr) + { +- enum XML_Error result = doContent(parser, 1, encoding, start, end, +- endPtr, (XML_Bool)!ps_finalBuffer); ++ enum XML_Error result = doContent(parser, 1, parser->m_encoding, start, end, ++ endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + if (result == XML_ERROR_NONE) { + if (!storeRawNames(parser)) + return XML_ERROR_NO_MEMORY; +@@ -2716,17 +2684,17 @@ doContent(XML_Parser parser, + XML_Bool haveMore) + { + /* save one level of indirection */ +- DTD * const dtd = _dtd; ++ DTD * const dtd = parser->m_dtd; + + const char **eventPP; + const char **eventEndPP; +- if (enc == encoding) { +- eventPP = &eventPtr; +- eventEndPP = &eventEndPtr; ++ if (enc == parser->m_encoding) { ++ eventPP = &parser->m_eventPtr; ++ eventEndPP = &parser->m_eventEndPtr; + } + else { +- eventPP = &(openInternalEntities->internalEventPtr); +- eventEndPP = &(openInternalEntities->internalEventEndPtr); ++ eventPP = &(parser->m_openInternalEntities->internalEventPtr); ++ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + } + *eventPP = s; + +@@ -2741,18 +2709,18 @@ doContent(XML_Parser parser, + return XML_ERROR_NONE; + } + *eventEndPP = end; +- if (characterDataHandler) { ++ if (parser->m_characterDataHandler) { + XML_Char c = 0xA; +- characterDataHandler(handlerArg, &c, 1); ++ parser->m_characterDataHandler(parser->m_handlerArg, &c, 1); + } +- else if (defaultHandler) ++ else if (parser->m_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) ++ if (parser->m_tagLevel != startTagLevel) + return XML_ERROR_ASYNC_ENTITY; + *nextPtr = end; + return XML_ERROR_NONE; +@@ -2762,7 +2730,7 @@ doContent(XML_Parser parser, + return XML_ERROR_NONE; + } + if (startTagLevel > 0) { +- if (tagLevel != startTagLevel) ++ if (parser->m_tagLevel != startTagLevel) + return XML_ERROR_ASYNC_ENTITY; + *nextPtr = s; + return XML_ERROR_NONE; +@@ -2791,9 +2759,9 @@ doContent(XML_Parser parser, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (ch) { +- if (characterDataHandler) +- characterDataHandler(handlerArg, &ch, 1); +- else if (defaultHandler) ++ if (parser->m_characterDataHandler) ++ parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1); ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + } +@@ -2815,9 +2783,9 @@ doContent(XML_Parser parser, + return XML_ERROR_ENTITY_DECLARED_IN_PE; + } + else if (!entity) { +- if (skippedEntityHandler) +- skippedEntityHandler(handlerArg, name, 0); +- else if (defaultHandler) ++ if (parser->m_skippedEntityHandler) ++ parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0); ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + } +@@ -2827,10 +2795,10 @@ doContent(XML_Parser parser, + 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) ++ if (!parser->m_defaultExpandInternalEntities) { ++ if (parser->m_skippedEntityHandler) ++ parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name, 0); ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + } +@@ -2838,22 +2806,22 @@ doContent(XML_Parser parser, + if (result != XML_ERROR_NONE) + return result; + } +- else if (externalEntityRefHandler) { ++ else if (parser->m_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, ++ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + context, + entity->base, + entity->systemId, + entity->publicId)) + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; +- poolDiscard(&tempPool); ++ poolDiscard(&parser->m_tempPool); + } +- else if (defaultHandler) ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + } +@@ -2864,29 +2832,29 @@ doContent(XML_Parser parser, + TAG *tag; + enum XML_Error result; + XML_Char *toPtr; +- if (freeTagList) { +- tag = freeTagList; +- freeTagList = freeTagList->parent; ++ if (parser->m_freeTagList) { ++ tag = parser->m_freeTagList; ++ parser->m_freeTagList = parser->m_freeTagList->parent; + } + else { +- tag = (TAG *)MALLOC(sizeof(TAG)); ++ tag = (TAG *)MALLOC(parser, sizeof(TAG)); + if (!tag) + return XML_ERROR_NO_MEMORY; +- tag->buf = (char *)MALLOC(INIT_TAG_BUF_SIZE); ++ tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE); + if (!tag->buf) { +- FREE(tag); ++ FREE(parser, tag); + return XML_ERROR_NO_MEMORY; + } + tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE; + } + tag->bindings = NULL; +- tag->parent = tagStack; +- tagStack = tag; ++ tag->parent = parser->m_tagStack; ++ parser->m_tagStack = tag; + tag->name.localPart = NULL; + tag->name.prefix = NULL; + tag->rawName = s + enc->minBytesPerChar; + tag->rawNameLength = XmlNameLength(enc, tag->rawName); +- ++tagLevel; ++ ++parser->m_tagLevel; + { + const char *rawNameEnd = tag->rawName + tag->rawNameLength; + const char *fromPtr = tag->rawName; +@@ -2904,7 +2872,7 @@ doContent(XML_Parser parser, + } + bufSize = (int)(tag->bufEnd - tag->buf) << 1; + { +- char *temp = (char *)REALLOC(tag->buf, bufSize); ++ char *temp = (char *)REALLOC(parser, tag->buf, bufSize); + if (temp == NULL) + return XML_ERROR_NO_MEMORY; + tag->buf = temp; +@@ -2918,12 +2886,12 @@ doContent(XML_Parser parser, + 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) ++ if (parser->m_startElementHandler) ++ parser->m_startElementHandler(parser->m_handlerArg, tag->name.str, ++ (const XML_Char **)parser->m_atts); ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); +- poolClear(&tempPool); ++ poolClear(&parser->m_tempPool); + break; + } + case XML_TOK_EMPTY_ELEMENT_NO_ATTS: +@@ -2935,45 +2903,49 @@ doContent(XML_Parser parser, + BINDING *bindings = NULL; + XML_Bool noElmHandlers = XML_TRUE; + TAG_NAME name; +- name.str = poolStoreString(&tempPool, enc, rawName, ++ name.str = poolStoreString(&parser->m_tempPool, enc, rawName, + rawName + XmlNameLength(enc, rawName)); + if (!name.str) + return XML_ERROR_NO_MEMORY; +- poolFinish(&tempPool); ++ poolFinish(&parser->m_tempPool); + result = storeAtts(parser, enc, s, &name, &bindings); + if (result != XML_ERROR_NONE) { + freeBindings(parser, bindings); + return result; + } +- poolFinish(&tempPool); +- if (startElementHandler) { +- startElementHandler(handlerArg, name.str, (const XML_Char **)atts); ++ poolFinish(&parser->m_tempPool); ++ if (parser->m_startElementHandler) { ++ parser->m_startElementHandler(parser->m_handlerArg, name.str, (const XML_Char **)parser->m_atts); + noElmHandlers = XML_FALSE; + } +- if (endElementHandler) { +- if (startElementHandler) ++ if (parser->m_endElementHandler) { ++ if (parser->m_startElementHandler) + *eventPP = *eventEndPP; +- endElementHandler(handlerArg, name.str); ++ parser->m_endElementHandler(parser->m_handlerArg, name.str); + noElmHandlers = XML_FALSE; + } +- if (noElmHandlers && defaultHandler) ++ if (noElmHandlers && parser->m_defaultHandler) + reportDefault(parser, enc, s, next); +- poolClear(&tempPool); ++ poolClear(&parser->m_tempPool); + freeBindings(parser, bindings); + } +- if (tagLevel == 0) +- return epilogProcessor(parser, next, end, nextPtr); ++ if ((parser->m_tagLevel == 0) && (parser->m_parsingStatus.parsing != XML_FINISHED)) { ++ if (parser->m_parsingStatus.parsing == XML_SUSPENDED) ++ parser->m_processor = epilogProcessor; ++ else ++ return epilogProcessor(parser, next, end, nextPtr); ++ } + break; + case XML_TOK_END_TAG: +- if (tagLevel == startTagLevel) ++ if (parser->m_tagLevel == startTagLevel) + return XML_ERROR_ASYNC_ENTITY; + else { + int len; + const char *rawName; +- TAG *tag = tagStack; +- tagStack = tag->parent; +- tag->parent = freeTagList; +- freeTagList = tag; ++ TAG *tag = parser->m_tagStack; ++ parser->m_tagStack = tag->parent; ++ tag->parent = parser->m_freeTagList; ++ parser->m_freeTagList = tag; + rawName = s + enc->minBytesPerChar*2; + len = XmlNameLength(enc, rawName); + if (len != tag->rawNameLength +@@ -2981,13 +2953,13 @@ doContent(XML_Parser parser, + *eventPP = rawName; + return XML_ERROR_TAG_MISMATCH; + } +- --tagLevel; +- if (endElementHandler) { ++ --parser->m_tagLevel; ++ if (parser->m_endElementHandler) { + const XML_Char *localPart; + const XML_Char *prefix; + XML_Char *uri; + localPart = tag->name.localPart; +- if (ns && localPart) { ++ if (parser->m_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 +@@ -2996,26 +2968,26 @@ doContent(XML_Parser parser, + /* 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; ++ if (parser->m_ns_triplets && prefix) { ++ *uri++ = parser->m_namespaceSeparator; + while (*prefix) *uri++ = *prefix++; + } + *uri = XML_T('\0'); + } +- endElementHandler(handlerArg, tag->name.str); ++ parser->m_endElementHandler(parser->m_handlerArg, tag->name.str); + } +- else if (defaultHandler) ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + while (tag->bindings) { + BINDING *b = tag->bindings; +- if (endNamespaceDeclHandler) +- endNamespaceDeclHandler(handlerArg, b->prefix->name); ++ if (parser->m_endNamespaceDeclHandler) ++ parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name); + tag->bindings = tag->bindings->nextTagBinding; +- b->nextTagBinding = freeBindingList; +- freeBindingList = b; ++ b->nextTagBinding = parser->m_freeBindingList; ++ parser->m_freeBindingList = b; + b->prefix->binding = b->prevPrefixBinding; + } +- if (tagLevel == 0) ++ if (parser->m_tagLevel == 0) + return epilogProcessor(parser, next, end, nextPtr); + } + break; +@@ -3024,29 +2996,29 @@ doContent(XML_Parser parser, + int n = XmlCharRefNumber(enc, s); + if (n < 0) + return XML_ERROR_BAD_CHAR_REF; +- if (characterDataHandler) { ++ if (parser->m_characterDataHandler) { + XML_Char buf[XML_ENCODE_MAX]; +- characterDataHandler(handlerArg, buf, XmlEncode(n, (ICHAR *)buf)); ++ parser->m_characterDataHandler(parser->m_handlerArg, buf, XmlEncode(n, (ICHAR *)buf)); + } +- else if (defaultHandler) ++ else if (parser->m_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) { ++ if (parser->m_characterDataHandler) { + XML_Char c = 0xA; +- characterDataHandler(handlerArg, &c, 1); ++ parser->m_characterDataHandler(parser->m_handlerArg, &c, 1); + } +- else if (defaultHandler) ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + case XML_TOK_CDATA_SECT_OPEN: + { + enum XML_Error result; +- if (startCdataSectionHandler) +- startCdataSectionHandler(handlerArg); ++ if (parser->m_startCdataSectionHandler) ++ parser->m_startCdataSectionHandler(parser->m_handlerArg); + #if 0 + /* Suppose you doing a transformation on a document that involves + changing only the character data. You set up a defaultHandler +@@ -3060,16 +3032,16 @@ doContent(XML_Parser parser, + 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); ++ else if (parser->m_characterDataHandler) ++ parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0); + #endif +- else if (defaultHandler) ++ else if (parser->m_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; ++ parser->m_processor = cdataSectionProcessor; + return result; + } + } +@@ -3079,19 +3051,19 @@ doContent(XML_Parser parser, + *nextPtr = s; + return XML_ERROR_NONE; + } +- if (characterDataHandler) { ++ if (parser->m_characterDataHandler) { + if (MUST_CONVERT(enc, s)) { +- ICHAR *dataPtr = (ICHAR *)dataBuf; +- XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd); +- characterDataHandler(handlerArg, dataBuf, +- (int)(dataPtr - (ICHAR *)dataBuf)); ++ ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf; ++ XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd); ++ parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, ++ (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + } + else +- characterDataHandler(handlerArg, ++ parser->m_characterDataHandler(parser->m_handlerArg, + (XML_Char *)s, + (int)((XML_Char *)end - (XML_Char *)s)); + } +- else if (defaultHandler) ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, end); + /* We are at the end of the final buffer, should we check for + XML_SUSPENDED, XML_FINISHED? +@@ -3100,7 +3072,7 @@ doContent(XML_Parser parser, + *eventPP = end; + return XML_ERROR_NO_ELEMENTS; + } +- if (tagLevel != startTagLevel) { ++ if (parser->m_tagLevel != startTagLevel) { + *eventPP = end; + return XML_ERROR_ASYNC_ENTITY; + } +@@ -3108,26 +3080,26 @@ doContent(XML_Parser parser, + return XML_ERROR_NONE; + case XML_TOK_DATA_CHARS: + { +- XML_CharacterDataHandler charDataHandler = characterDataHandler; ++ XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler; + if (charDataHandler) { + if (MUST_CONVERT(enc, s)) { + for (;;) { +- ICHAR *dataPtr = (ICHAR *)dataBuf; +- const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd); ++ ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf; ++ const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd); + *eventEndPP = s; +- charDataHandler(handlerArg, dataBuf, +- (int)(dataPtr - (ICHAR *)dataBuf)); ++ charDataHandler(parser->m_handlerArg, parser->m_dataBuf, ++ (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) + break; + *eventPP = s; + } + } + else +- charDataHandler(handlerArg, ++ charDataHandler(parser->m_handlerArg, + (XML_Char *)s, + (int)((XML_Char *)next - (XML_Char *)s)); + } +- else if (defaultHandler) ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + } + break; +@@ -3147,13 +3119,13 @@ doContent(XML_Parser parser, + * + * LCOV_EXCL_START + */ +- if (defaultHandler) ++ if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + /* LCOV_EXCL_STOP */ + } + *eventPP = s = next; +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *nextPtr = next; + return XML_ERROR_NONE; +@@ -3166,7 +3138,7 @@ doContent(XML_Parser parser, + } + + /* This function does not call free() on the allocated memory, merely +- * moving it to the parser's freeBindingList where it can be freed or ++ * moving it to the parser's m_freeBindingList where it can be freed or + * reused as appropriate. + */ + static void +@@ -3175,15 +3147,15 @@ freeBindings(XML_Parser parser, BINDING *bindings) + while (bindings) { + BINDING *b = bindings; + +- /* startNamespaceDeclHandler will have been called for this ++ /* m_startNamespaceDeclHandler will have been called for this + * binding in addBindings(), so call the end handler now. + */ +- if (endNamespaceDeclHandler) +- endNamespaceDeclHandler(handlerArg, b->prefix->name); ++ if (parser->m_endNamespaceDeclHandler) ++ parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name); + + bindings = bindings->nextTagBinding; +- b->nextTagBinding = freeBindingList; +- freeBindingList = b; ++ b->nextTagBinding = parser->m_freeBindingList; ++ parser->m_freeBindingList = b; + b->prefix->binding = b->prevPrefixBinding; + } + } +@@ -3203,7 +3175,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + const char *attStr, TAG_NAME *tagNamePtr, + BINDING **bindingsPtr) + { +- DTD * const dtd = _dtd; /* save one level of indirection */ ++ DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + ELEMENT_TYPE *elementType; + int nDefaultAtts; + const XML_Char **appAtts; /* the attribute list for the application */ +@@ -3226,43 +3198,43 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + sizeof(ELEMENT_TYPE)); + if (!elementType) + return XML_ERROR_NO_MEMORY; +- if (ns && !setElementTypePrefix(parser, elementType)) ++ if (parser->m_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; ++ n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts); ++ if (n + nDefaultAtts > parser->m_attsSize) { ++ int oldAttsSize = parser->m_attsSize; + ATTRIBUTE *temp; + #ifdef XML_ATTR_INFO + XML_AttrInfo *temp2; + #endif +- attsSize = n + nDefaultAtts + INIT_ATTS_SIZE; +- temp = (ATTRIBUTE *)REALLOC((void *)atts, attsSize * sizeof(ATTRIBUTE)); ++ parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE; ++ temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts, parser->m_attsSize * sizeof(ATTRIBUTE)); + if (temp == NULL) { +- attsSize = oldAttsSize; ++ parser->m_attsSize = oldAttsSize; + return XML_ERROR_NO_MEMORY; + } +- atts = temp; ++ parser->m_atts = temp; + #ifdef XML_ATTR_INFO +- temp2 = (XML_AttrInfo *)REALLOC((void *)attInfo, attsSize * sizeof(XML_AttrInfo)); ++ temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo, parser->m_attsSize * sizeof(XML_AttrInfo)); + if (temp2 == NULL) { +- attsSize = oldAttsSize; ++ parser->m_attsSize = oldAttsSize; + return XML_ERROR_NO_MEMORY; + } +- attInfo = temp2; ++ parser->m_attInfo = temp2; + #endif + if (n > oldAttsSize) +- XmlGetAttributes(enc, attStr, n, atts); ++ XmlGetAttributes(enc, attStr, n, parser->m_atts); + } + +- appAtts = (const XML_Char **)atts; ++ appAtts = (const XML_Char **)parser->m_atts; + for (i = 0; i < n; i++) { +- ATTRIBUTE *currAtt = &atts[i]; ++ ATTRIBUTE *currAtt = &parser->m_atts[i]; + #ifdef XML_ATTR_INFO +- XML_AttrInfo *currAttInfo = &attInfo[i]; ++ XML_AttrInfo *currAttInfo = &parser->m_attInfo[i]; + #endif + /* add the name and value to the attribute list */ + ATTRIBUTE_ID *attId = getAttributeId(parser, enc, currAtt->name, +@@ -3271,25 +3243,25 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + if (!attId) + return XML_ERROR_NO_MEMORY; + #ifdef XML_ATTR_INFO +- currAttInfo->nameStart = parseEndByteIndex - (parseEndPtr - currAtt->name); ++ currAttInfo->nameStart = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name); + currAttInfo->nameEnd = currAttInfo->nameStart + + XmlNameLength(enc, currAtt->name); +- currAttInfo->valueStart = parseEndByteIndex - +- (parseEndPtr - currAtt->valuePtr); +- currAttInfo->valueEnd = parseEndByteIndex - (parseEndPtr - currAtt->valueEnd); ++ currAttInfo->valueStart = parser->m_parseEndByteIndex - ++ (parser->m_parseEndPtr - currAtt->valuePtr); ++ currAttInfo->valueEnd = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->valueEnd); + #endif + /* 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; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = parser->m_atts[i].name; + return XML_ERROR_DUPLICATE_ATTRIBUTE; + } + (attId->name)[-1] = 1; + appAtts[attIndex++] = attId->name; +- if (!atts[i].normalized) { ++ if (!parser->m_atts[i].normalized) { + enum XML_Error result; + XML_Bool isCdata = XML_TRUE; + +@@ -3306,20 +3278,20 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + + /* normalize the attribute value */ + result = storeAttributeValue(parser, enc, isCdata, +- atts[i].valuePtr, atts[i].valueEnd, +- &tempPool); ++ parser->m_atts[i].valuePtr, parser->m_atts[i].valueEnd, ++ &parser->m_tempPool); + if (result) + return result; +- appAtts[attIndex] = poolStart(&tempPool); +- poolFinish(&tempPool); ++ appAtts[attIndex] = poolStart(&parser->m_tempPool); ++ poolFinish(&parser->m_tempPool); + } + else { + /* the value did not need normalizing */ +- appAtts[attIndex] = poolStoreString(&tempPool, enc, atts[i].valuePtr, +- atts[i].valueEnd); ++ appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc, parser->m_atts[i].valuePtr, ++ parser->m_atts[i].valueEnd); + if (appAtts[attIndex] == 0) + return XML_ERROR_NO_MEMORY; +- poolFinish(&tempPool); ++ poolFinish(&parser->m_tempPool); + } + /* handle prefixed attribute names */ + if (attId->prefix) { +@@ -3343,16 +3315,16 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + } + + /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */ +- nSpecifiedAtts = attIndex; ++ parser->m_nSpecifiedAtts = attIndex; + if (elementType->idAtt && (elementType->idAtt->name)[-1]) { + for (i = 0; i < attIndex; i += 2) + if (appAtts[i] == elementType->idAtt->name) { +- idAttIndex = i; ++ parser->m_idAttIndex = i; + break; + } + } + else +- idAttIndex = -1; ++ parser->m_idAttIndex = -1; + + /* do attribute defaulting */ + for (i = 0; i < nDefaultAtts; i++) { +@@ -3386,33 +3358,33 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + i = 0; + if (nPrefixes) { + int j; /* hash table index */ +- unsigned long version = nsAttsVersion; +- int nsAttsSize = (int)1 << nsAttsPower; +- unsigned char oldNsAttsPower = nsAttsPower; ++ unsigned long version = parser->m_nsAttsVersion; ++ int nsAttsSize = (int)1 << parser->m_nsAttsPower; ++ unsigned char oldNsAttsPower = parser->m_nsAttsPower; + /* size of hash table must be at least 2 * (# of prefixed attributes) */ +- if ((nPrefixes << 1) >> nsAttsPower) { /* true for nsAttsPower = 0 */ ++ if ((nPrefixes << 1) >> parser->m_nsAttsPower) { /* true for m_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)); ++ while (nPrefixes >> parser->m_nsAttsPower++); ++ if (parser->m_nsAttsPower < 3) ++ parser->m_nsAttsPower = 3; ++ nsAttsSize = (int)1 << parser->m_nsAttsPower; ++ temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT)); + if (!temp) { +- /* Restore actual size of memory in nsAtts */ +- nsAttsPower = oldNsAttsPower; ++ /* Restore actual size of memory in m_nsAtts */ ++ parser->m_nsAttsPower = oldNsAttsPower; + return XML_ERROR_NO_MEMORY; + } +- nsAtts = temp; +- version = 0; /* force re-initialization of nsAtts hash table */ ++ parser->m_nsAtts = temp; ++ version = 0; /* force re-initialization of m_nsAtts hash table */ + } +- /* using a version flag saves us from initializing nsAtts every time */ ++ /* using a version flag saves us from initializing m_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; ++ parser->m_nsAtts[--j].version = version; + } +- nsAttsVersion = --version; ++ parser->m_nsAttsVersion = --version; + + /* expand prefixed names and check for duplicates */ + for (; i < attIndex; i += 2) { +@@ -3452,7 +3424,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + + for (j = 0; j < b->uriLen; j++) { + const XML_Char c = b->uri[j]; +- if (!poolAppendChar(&tempPool, c)) ++ if (!poolAppendChar(&parser->m_tempPool, c)) + return XML_ERROR_NO_MEMORY; + } + +@@ -3464,7 +3436,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char)); + + do { /* copies null terminator */ +- if (!poolAppendChar(&tempPool, *s)) ++ if (!poolAppendChar(&parser->m_tempPool, *s)) + return XML_ERROR_NO_MEMORY; + } while (*s++); + +@@ -3476,40 +3448,40 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + unsigned char step = 0; + unsigned long mask = nsAttsSize - 1; + j = uriHash & mask; /* index into hash table */ +- while (nsAtts[j].version == version) { ++ while (parser->m_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; ++ if (uriHash == parser->m_nsAtts[j].hash) { ++ const XML_Char *s1 = poolStart(&parser->m_tempPool); ++ const XML_Char *s2 = parser->m_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); ++ step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower); + j < step ? (j += nsAttsSize - step) : (j -= step); + } + } + +- if (ns_triplets) { /* append namespace separator and prefix */ +- tempPool.ptr[-1] = namespaceSeparator; ++ if (parser->m_ns_triplets) { /* append namespace separator and prefix */ ++ parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator; + s = b->prefix->name; + do { +- if (!poolAppendChar(&tempPool, *s)) ++ if (!poolAppendChar(&parser->m_tempPool, *s)) + return XML_ERROR_NO_MEMORY; + } while (*s++); + } + + /* store expanded name in attribute list */ +- s = poolStart(&tempPool); +- poolFinish(&tempPool); ++ s = poolStart(&parser->m_tempPool); ++ poolFinish(&parser->m_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; ++ parser->m_nsAtts[j].version = version; ++ parser->m_nsAtts[j].hash = uriHash; ++ parser->m_nsAtts[j].uriName = s; + + if (!--nPrefixes) { + i += 2; +@@ -3526,7 +3498,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding) + binding->attId->name[-1] = 0; + +- if (!ns) ++ if (!parser->m_ns) + return XML_ERROR_NONE; + + /* expand the element type name */ +@@ -3545,7 +3517,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + else + return XML_ERROR_NONE; + prefixLen = 0; +- if (ns_triplets && binding->prefix->name) { ++ if (parser->m_ns_triplets && binding->prefix->name) { + for (; binding->prefix->name[prefixLen++];) + ; /* prefixLen includes null terminator */ + } +@@ -3558,24 +3530,24 @@ storeAtts(XML_Parser parser, const ENCODING *enc, + n = i + binding->uriLen + prefixLen; + if (n > binding->uriAlloc) { + TAG *p; +- uri = (XML_Char *)MALLOC((n + EXPAND_SPARE) * sizeof(XML_Char)); ++ uri = (XML_Char *)MALLOC(parser, (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) ++ for (p = parser->m_tagStack; p; p = p->parent) + if (p->name.str == binding->uri) + p->name.str = uri; +- FREE(binding->uri); ++ FREE(parser, binding->uri); + binding->uri = uri; + } +- /* if namespaceSeparator != '\0' then uri includes it already */ ++ /* if m_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 */ ++ *uri = parser->m_namespaceSeparator; /* replace null terminator */ + memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char)); + } + tagNamePtr->str = binding->uri; +@@ -3653,48 +3625,48 @@ addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, + if (isXMLNS) + return XML_ERROR_RESERVED_NAMESPACE_URI; + +- if (namespaceSeparator) ++ if (parser->m_namespaceSeparator) + len++; +- if (freeBindingList) { +- b = freeBindingList; ++ if (parser->m_freeBindingList) { ++ b = parser->m_freeBindingList; + if (len > b->uriAlloc) { +- XML_Char *temp = (XML_Char *)REALLOC(b->uri, ++ XML_Char *temp = (XML_Char *)REALLOC(parser, 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; ++ parser->m_freeBindingList = b->nextTagBinding; + } + else { +- b = (BINDING *)MALLOC(sizeof(BINDING)); ++ b = (BINDING *)MALLOC(parser, sizeof(BINDING)); + if (!b) + return XML_ERROR_NO_MEMORY; +- b->uri = (XML_Char *)MALLOC(sizeof(XML_Char) * (len + EXPAND_SPARE)); ++ b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE)); + if (!b->uri) { +- FREE(b); ++ FREE(parser, 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; ++ if (parser->m_namespaceSeparator) ++ b->uri[len - 1] = parser->m_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) ++ if (*uri == XML_T('\0') && prefix == &parser->m_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, ++ if (attId && parser->m_startNamespaceDeclHandler) ++ parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name, + prefix->binding ? uri : 0); + return XML_ERROR_NONE; + } +@@ -3708,17 +3680,17 @@ cdataSectionProcessor(XML_Parser parser, + const char *end, + const char **endPtr) + { +- enum XML_Error result = doCdataSection(parser, encoding, &start, end, +- endPtr, (XML_Bool)!ps_finalBuffer); ++ enum XML_Error result = doCdataSection(parser, parser->m_encoding, &start, end, ++ endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + if (result != XML_ERROR_NONE) + return result; + if (start) { +- if (parentParser) { /* we are parsing an external entity */ +- processor = externalEntityContentProcessor; ++ if (parser->m_parentParser) { /* we are parsing an external entity */ ++ parser->m_processor = externalEntityContentProcessor; + return externalEntityContentProcessor(parser, start, end, endPtr); + } + else { +- processor = contentProcessor; ++ parser->m_processor = contentProcessor; + return contentProcessor(parser, start, end, endPtr); + } + } +@@ -3739,14 +3711,14 @@ doCdataSection(XML_Parser parser, + const char *s = *startPtr; + const char **eventPP; + const char **eventEndPP; +- if (enc == encoding) { +- eventPP = &eventPtr; ++ if (enc == parser->m_encoding) { ++ eventPP = &parser->m_eventPtr; + *eventPP = s; +- eventEndPP = &eventEndPtr; ++ eventEndPP = &parser->m_eventEndPtr; + } + else { +- eventPP = &(openInternalEntities->internalEventPtr); +- eventEndPP = &(openInternalEntities->internalEventEndPtr); ++ eventPP = &(parser->m_openInternalEntities->internalEventPtr); ++ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + } + *eventPP = s; + *startPtr = NULL; +@@ -3757,51 +3729,51 @@ doCdataSection(XML_Parser parser, + *eventEndPP = next; + switch (tok) { + case XML_TOK_CDATA_SECT_CLOSE: +- if (endCdataSectionHandler) +- endCdataSectionHandler(handlerArg); ++ if (parser->m_endCdataSectionHandler) ++ parser->m_endCdataSectionHandler(parser->m_handlerArg); + #if 0 + /* see comment under XML_TOK_CDATA_SECT_OPEN */ +- else if (characterDataHandler) +- characterDataHandler(handlerArg, dataBuf, 0); ++ else if (parser->m_characterDataHandler) ++ parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0); + #endif +- else if (defaultHandler) ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + *startPtr = next; + *nextPtr = next; +- if (ps_parsing == XML_FINISHED) ++ if (parser->m_parsingStatus.parsing == XML_FINISHED) + return XML_ERROR_ABORTED; + else + return XML_ERROR_NONE; + case XML_TOK_DATA_NEWLINE: +- if (characterDataHandler) { ++ if (parser->m_characterDataHandler) { + XML_Char c = 0xA; +- characterDataHandler(handlerArg, &c, 1); ++ parser->m_characterDataHandler(parser->m_handlerArg, &c, 1); + } +- else if (defaultHandler) ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + case XML_TOK_DATA_CHARS: + { +- XML_CharacterDataHandler charDataHandler = characterDataHandler; ++ XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler; + if (charDataHandler) { + if (MUST_CONVERT(enc, s)) { + for (;;) { +- ICHAR *dataPtr = (ICHAR *)dataBuf; +- const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd); ++ ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf; ++ const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd); + *eventEndPP = next; +- charDataHandler(handlerArg, dataBuf, +- (int)(dataPtr - (ICHAR *)dataBuf)); ++ charDataHandler(parser->m_handlerArg, parser->m_dataBuf, ++ (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) + break; + *eventPP = s; + } + } + else +- charDataHandler(handlerArg, ++ charDataHandler(parser->m_handlerArg, + (XML_Char *)s, + (int)((XML_Char *)next - (XML_Char *)s)); + } +- else if (defaultHandler) ++ else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + } + break; +@@ -3835,7 +3807,7 @@ doCdataSection(XML_Parser parser, + } + + *eventPP = s = next; +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *nextPtr = next; + return XML_ERROR_NONE; +@@ -3858,12 +3830,12 @@ ignoreSectionProcessor(XML_Parser parser, + const char *end, + const char **endPtr) + { +- enum XML_Error result = doIgnoreSection(parser, encoding, &start, end, +- endPtr, (XML_Bool)!ps_finalBuffer); ++ enum XML_Error result = doIgnoreSection(parser, parser->m_encoding, &start, end, ++ endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + if (result != XML_ERROR_NONE) + return result; + if (start) { +- processor = prologProcessor; ++ parser->m_processor = prologProcessor; + return prologProcessor(parser, start, end, endPtr); + } + return result; +@@ -3885,15 +3857,15 @@ doIgnoreSection(XML_Parser parser, + const char *s = *startPtr; + const char **eventPP; + const char **eventEndPP; +- if (enc == encoding) { +- eventPP = &eventPtr; ++ if (enc == parser->m_encoding) { ++ eventPP = &parser->m_eventPtr; + *eventPP = s; +- eventEndPP = &eventEndPtr; ++ eventEndPP = &parser->m_eventEndPtr; + } + else { + /* It's not entirely clear, but it seems the following two lines + * of code cannot be executed. The only occasions on which 'enc' +- * is not 'parser->m_encoding' are when this function is called ++ * is not 'encoding' are when this function is called + * from the internal entity processing, and IGNORE sections are an + * error in internal entities. + * +@@ -3902,8 +3874,8 @@ doIgnoreSection(XML_Parser parser, + * + * LCOV_EXCL_START + */ +- eventPP = &(openInternalEntities->internalEventPtr); +- eventEndPP = &(openInternalEntities->internalEventEndPtr); ++ eventPP = &(parser->m_openInternalEntities->internalEventPtr); ++ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + /* LCOV_EXCL_STOP */ + } + *eventPP = s; +@@ -3912,11 +3884,11 @@ doIgnoreSection(XML_Parser parser, + *eventEndPP = next; + switch (tok) { + case XML_TOK_IGNORE_SECT: +- if (defaultHandler) ++ if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + *startPtr = next; + *nextPtr = next; +- if (ps_parsing == XML_FINISHED) ++ if (parser->m_parsingStatus.parsing == XML_FINISHED) + return XML_ERROR_ABORTED; + else + return XML_ERROR_NONE; +@@ -3960,27 +3932,27 @@ initializeEncoding(XML_Parser parser) + #ifdef XML_UNICODE + char encodingBuf[128]; + /* See comments abount `protoclEncodingName` in parserInit() */ +- if (!protocolEncodingName) ++ if (!parser->m_protocolEncodingName) + s = NULL; + else { + int i; +- for (i = 0; protocolEncodingName[i]; i++) { ++ for (i = 0; parser->m_protocolEncodingName[i]; i++) { + if (i == sizeof(encodingBuf) - 1 +- || (protocolEncodingName[i] & ~0x7f) != 0) { ++ || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) { + encodingBuf[0] = '\0'; + break; + } +- encodingBuf[i] = (char)protocolEncodingName[i]; ++ encodingBuf[i] = (char)parser->m_protocolEncodingName[i]; + } + encodingBuf[i] = '\0'; + s = encodingBuf; + } + #else +- s = protocolEncodingName; ++ s = parser->m_protocolEncodingName; + #endif +- if ((ns ? XmlInitEncodingNS : XmlInitEncoding)(&initEncoding, &encoding, s)) ++ if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(&parser->m_initEncoding, &parser->m_encoding, s)) + return XML_ERROR_NONE; +- return handleUnknownEncoding(parser, protocolEncodingName); ++ return handleUnknownEncoding(parser, parser->m_protocolEncodingName); + } + + static enum XML_Error +@@ -3994,13 +3966,13 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity, + const char *versionend; + const XML_Char *storedversion = NULL; + int standalone = -1; +- if (!(ns ++ if (!(parser->m_ns + ? XmlParseXmlDeclNS + : XmlParseXmlDecl)(isGeneralTextEntity, +- encoding, ++ parser->m_encoding, + s, + next, +- &eventPtr, ++ &parser->m_eventPtr, + &version, + &versionend, + &encodingName, +@@ -4012,69 +3984,69 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity, + return XML_ERROR_XML_DECL; + } + if (!isGeneralTextEntity && standalone == 1) { +- _dtd->standalone = XML_TRUE; ++ parser->m_dtd->standalone = XML_TRUE; + #ifdef XML_DTD +- if (paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE) +- paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; ++ if (parser->m_paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE) ++ parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; + #endif /* XML_DTD */ + } +- if (xmlDeclHandler) { ++ if (parser->m_xmlDeclHandler) { + if (encodingName != NULL) { +- storedEncName = poolStoreString(&temp2Pool, +- encoding, ++ storedEncName = poolStoreString(&parser->m_temp2Pool, ++ parser->m_encoding, + encodingName, + encodingName +- + XmlNameLength(encoding, encodingName)); ++ + XmlNameLength(parser->m_encoding, encodingName)); + if (!storedEncName) + return XML_ERROR_NO_MEMORY; +- poolFinish(&temp2Pool); ++ poolFinish(&parser->m_temp2Pool); + } + if (version) { +- storedversion = poolStoreString(&temp2Pool, +- encoding, ++ storedversion = poolStoreString(&parser->m_temp2Pool, ++ parser->m_encoding, + version, +- versionend - encoding->minBytesPerChar); ++ versionend - parser->m_encoding->minBytesPerChar); + if (!storedversion) + return XML_ERROR_NO_MEMORY; + } +- xmlDeclHandler(handlerArg, storedversion, storedEncName, standalone); ++ parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName, standalone); + } +- else if (defaultHandler) +- reportDefault(parser, encoding, s, next); +- if (protocolEncodingName == NULL) { ++ else if (parser->m_defaultHandler) ++ reportDefault(parser, parser->m_encoding, s, next); ++ if (parser->m_protocolEncodingName == NULL) { + if (newEncoding) { + /* Check that the specified encoding does not conflict with what + * the parser has already deduced. Do we have the same number + * of bytes in the smallest representation of a character? If + * this is UTF-16, is it the same endianness? + */ +- if (newEncoding->minBytesPerChar != encoding->minBytesPerChar ++ if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar + || (newEncoding->minBytesPerChar == 2 && +- newEncoding != encoding)) { +- eventPtr = encodingName; ++ newEncoding != parser->m_encoding)) { ++ parser->m_eventPtr = encodingName; + return XML_ERROR_INCORRECT_ENCODING; + } +- encoding = newEncoding; ++ parser->m_encoding = newEncoding; + } + else if (encodingName) { + enum XML_Error result; + if (!storedEncName) { + storedEncName = poolStoreString( +- &temp2Pool, encoding, encodingName, +- encodingName + XmlNameLength(encoding, encodingName)); ++ &parser->m_temp2Pool, parser->m_encoding, encodingName, ++ encodingName + XmlNameLength(parser->m_encoding, encodingName)); + if (!storedEncName) + return XML_ERROR_NO_MEMORY; + } + result = handleUnknownEncoding(parser, storedEncName); +- poolClear(&temp2Pool); ++ poolClear(&parser->m_temp2Pool); + if (result == XML_ERROR_UNKNOWN_ENCODING) +- eventPtr = encodingName; ++ parser->m_eventPtr = encodingName; + return result; + } + } + + if (storedEncName || storedversion) +- poolClear(&temp2Pool); ++ poolClear(&parser->m_temp2Pool); + + return XML_ERROR_NONE; + } +@@ -4082,7 +4054,7 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity, + static enum XML_Error + handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) + { +- if (unknownEncodingHandler) { ++ if (parser->m_unknownEncodingHandler) { + XML_Encoding info; + int i; + for (i = 0; i < 256; i++) +@@ -4090,25 +4062,25 @@ handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) + info.convert = NULL; + info.data = NULL; + info.release = NULL; +- if (unknownEncodingHandler(unknownEncodingHandlerData, encodingName, ++ if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData, encodingName, + &info)) { + ENCODING *enc; +- unknownEncodingMem = MALLOC(XmlSizeOfUnknownEncoding()); +- if (!unknownEncodingMem) { ++ parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding()); ++ if (!parser->m_unknownEncodingMem) { + if (info.release) + info.release(info.data); + return XML_ERROR_NO_MEMORY; + } +- enc = (ns ++ enc = (parser->m_ns + ? XmlInitUnknownEncodingNS +- : XmlInitUnknownEncoding)(unknownEncodingMem, ++ : XmlInitUnknownEncoding)(parser->m_unknownEncodingMem, + info.map, + info.convert, + info.data); + if (enc) { +- unknownEncodingData = info.data; +- unknownEncodingRelease = info.release; +- encoding = enc; ++ parser->m_unknownEncodingData = info.data; ++ parser->m_unknownEncodingRelease = info.release; ++ parser->m_encoding = enc; + return XML_ERROR_NONE; + } + } +@@ -4127,7 +4099,7 @@ prologInitProcessor(XML_Parser parser, + enum XML_Error result = initializeEncoding(parser); + if (result != XML_ERROR_NONE) + return result; +- processor = prologProcessor; ++ parser->m_processor = prologProcessor; + return prologProcessor(parser, s, end, nextPtr); + } + +@@ -4145,14 +4117,14 @@ externalParEntInitProcessor(XML_Parser parser, + + /* we know now that XML_Parse(Buffer) has been called, + so we consider the external parameter entity read */ +- _dtd->paramEntityRead = XML_TRUE; ++ parser->m_dtd->paramEntityRead = XML_TRUE; + +- if (prologState.inEntityValue) { +- processor = entityValueInitProcessor; ++ if (parser->m_prologState.inEntityValue) { ++ parser->m_processor = entityValueInitProcessor; + return entityValueInitProcessor(parser, s, end, nextPtr); + } + else { +- processor = externalParEntProcessor; ++ parser->m_processor = externalParEntProcessor; + return externalParEntProcessor(parser, s, end, nextPtr); + } + } +@@ -4166,13 +4138,13 @@ entityValueInitProcessor(XML_Parser parser, + int tok; + const char *start = s; + const char *next = start; +- eventPtr = start; ++ parser->m_eventPtr = start; + + for (;;) { +- tok = XmlPrologTok(encoding, start, end, &next); +- eventEndPtr = next; ++ tok = XmlPrologTok(parser->m_encoding, start, end, &next); ++ parser->m_eventEndPtr = next; + if (tok <= 0) { +- if (!ps_finalBuffer && tok != XML_TOK_INVALID) { ++ if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { + *nextPtr = s; + return XML_ERROR_NONE; + } +@@ -4188,23 +4160,23 @@ entityValueInitProcessor(XML_Parser parser, + break; + } + /* found end of entity value - can store it now */ +- return storeEntityValue(parser, encoding, s, end); ++ return storeEntityValue(parser, parser->m_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; +- /* At this point, ps_parsing cannot be XML_SUSPENDED. For that ++ /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For that + * to happen, a parameter entity parsing handler must have + * attempted to suspend the parser, which fails and raises an + * error. The parser can be aborted, but can't be suspended. + */ +- if (ps_parsing == XML_FINISHED) ++ if (parser->m_parsingStatus.parsing == XML_FINISHED) + return XML_ERROR_ABORTED; + *nextPtr = next; + /* stop scanning for text declaration - we found one */ +- processor = entityValueProcessor; ++ parser->m_processor = entityValueProcessor; + return entityValueProcessor(parser, next, end, nextPtr); + } + /* If we are at the end of the buffer, this would cause XmlPrologTok to +@@ -4214,7 +4186,7 @@ entityValueInitProcessor(XML_Parser parser, + 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) { ++ else if (tok == XML_TOK_BOM && next == end && !parser->m_parsingStatus.finalBuffer) { + *nextPtr = next; + return XML_ERROR_NONE; + } +@@ -4227,7 +4199,7 @@ entityValueInitProcessor(XML_Parser parser, + return XML_ERROR_SYNTAX; + } + start = next; +- eventPtr = start; ++ parser->m_eventPtr = start; + } + } + +@@ -4240,9 +4212,9 @@ externalParEntProcessor(XML_Parser parser, + const char *next = s; + int tok; + +- tok = XmlPrologTok(encoding, s, end, &next); ++ tok = XmlPrologTok(parser->m_encoding, s, end, &next); + if (tok <= 0) { +- if (!ps_finalBuffer && tok != XML_TOK_INVALID) { ++ if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { + *nextPtr = s; + return XML_ERROR_NONE; + } +@@ -4264,12 +4236,12 @@ externalParEntProcessor(XML_Parser parser, + */ + else if (tok == XML_TOK_BOM) { + s = next; +- tok = XmlPrologTok(encoding, s, end, &next); ++ tok = XmlPrologTok(parser->m_encoding, s, end, &next); + } + +- processor = prologProcessor; +- return doProlog(parser, encoding, s, end, tok, next, +- nextPtr, (XML_Bool)!ps_finalBuffer); ++ parser->m_processor = prologProcessor; ++ return doProlog(parser, parser->m_encoding, s, end, tok, next, ++ nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + } + + static enum XML_Error PTRCALL +@@ -4280,13 +4252,13 @@ entityValueProcessor(XML_Parser parser, + { + const char *start = s; + const char *next = s; +- const ENCODING *enc = encoding; ++ const ENCODING *enc = parser->m_encoding; + int tok; + + for (;;) { + tok = XmlPrologTok(enc, start, end, &next); + if (tok <= 0) { +- if (!ps_finalBuffer && tok != XML_TOK_INVALID) { ++ if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { + *nextPtr = s; + return XML_ERROR_NONE; + } +@@ -4317,9 +4289,9 @@ prologProcessor(XML_Parser parser, + 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); ++ int tok = XmlPrologTok(parser->m_encoding, s, end, &next); ++ return doProlog(parser, parser->m_encoding, s, end, tok, next, ++ nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + } + + static enum XML_Error +@@ -4356,19 +4328,19 @@ doProlog(XML_Parser parser, + static const XML_Char enumValueStart[] = { ASCII_LPAREN, '\0' }; + + /* save one level of indirection */ +- DTD * const dtd = _dtd; ++ DTD * const dtd = parser->m_dtd; + + const char **eventPP; + const char **eventEndPP; + enum XML_Content_Quant quant; + +- if (enc == encoding) { +- eventPP = &eventPtr; +- eventEndPP = &eventEndPtr; ++ if (enc == parser->m_encoding) { ++ eventPP = &parser->m_eventPtr; ++ eventEndPP = &parser->m_eventEndPtr; + } + else { +- eventPP = &(openInternalEntities->internalEventPtr); +- eventEndPP = &(openInternalEntities->internalEventEndPtr); ++ eventPP = &(parser->m_openInternalEntities->internalEventPtr); ++ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + } + + for (;;) { +@@ -4395,7 +4367,7 @@ doProlog(XML_Parser parser, + case XML_TOK_NONE: + #ifdef XML_DTD + /* for internal PE NOT referenced between declarations */ +- if (enc != encoding && !openInternalEntities->betweenDecl) { ++ if (enc != parser->m_encoding && !parser->m_openInternalEntities->betweenDecl) { + *nextPtr = s; + return XML_ERROR_NONE; + } +@@ -4403,8 +4375,8 @@ doProlog(XML_Parser parser, + 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) ++ if (parser->m_isParamEntity || enc != parser->m_encoding) { ++ if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc) + == XML_ROLE_ERROR) + return XML_ERROR_INCOMPLETE_PE; + *nextPtr = s; +@@ -4418,34 +4390,34 @@ doProlog(XML_Parser parser, + break; + } + } +- role = XmlTokenRole(&prologState, tok, s, next, enc); ++ role = XmlTokenRole(&parser->m_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; ++ enc = parser->m_encoding; + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_DOCTYPE_NAME: +- if (startDoctypeDeclHandler) { +- doctypeName = poolStoreString(&tempPool, enc, s, next); +- if (!doctypeName) ++ if (parser->m_startDoctypeDeclHandler) { ++ parser->m_doctypeName = poolStoreString(&parser->m_tempPool, enc, s, next); ++ if (!parser->m_doctypeName) + return XML_ERROR_NO_MEMORY; +- poolFinish(&tempPool); +- doctypePubid = NULL; ++ poolFinish(&parser->m_tempPool); ++ parser->m_doctypePubid = NULL; + handleDefault = XML_FALSE; + } +- doctypeSysid = NULL; /* always initialize to NULL */ ++ parser->m_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); ++ if (parser->m_startDoctypeDeclHandler) { ++ parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid, ++ parser->m_doctypePubid, 1); ++ parser->m_doctypeName = NULL; ++ poolClear(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + break; +@@ -4455,34 +4427,34 @@ doProlog(XML_Parser parser, + enum XML_Error result = processXmlDecl(parser, 1, s, next); + if (result != XML_ERROR_NONE) + return result; +- enc = encoding; ++ enc = parser->m_encoding; + handleDefault = XML_FALSE; + } + break; + #endif /* XML_DTD */ + case XML_ROLE_DOCTYPE_PUBLIC_ID: + #ifdef XML_DTD +- useForeignDTD = XML_FALSE; +- declEntity = (ENTITY *)lookup(parser, ++ parser->m_useForeignDTD = XML_FALSE; ++ parser->m_declEntity = (ENTITY *)lookup(parser, + &dtd->paramEntities, + externalSubsetName, + sizeof(ENTITY)); +- if (!declEntity) ++ if (!parser->m_declEntity) + return XML_ERROR_NO_MEMORY; + #endif /* XML_DTD */ + dtd->hasParamEntityRefs = XML_TRUE; +- if (startDoctypeDeclHandler) { ++ if (parser->m_startDoctypeDeclHandler) { + XML_Char *pubId; + if (!XmlIsPublicId(enc, s, next, eventPP)) + return XML_ERROR_PUBLICID; +- pubId = poolStoreString(&tempPool, enc, ++ pubId = poolStoreString(&parser->m_tempPool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!pubId) + return XML_ERROR_NO_MEMORY; + normalizePublicId(pubId); +- poolFinish(&tempPool); +- doctypePubid = pubId; ++ poolFinish(&parser->m_tempPool); ++ parser->m_doctypePubid = pubId; + handleDefault = XML_FALSE; + goto alreadyChecked; + } +@@ -4491,7 +4463,7 @@ doProlog(XML_Parser parser, + if (!XmlIsPublicId(enc, s, next, eventPP)) + return XML_ERROR_PUBLICID; + alreadyChecked: +- if (dtd->keepProcessing && declEntity) { ++ if (dtd->keepProcessing && parser->m_declEntity) { + XML_Char *tem = poolStoreString(&dtd->pool, + enc, + s + enc->minBytesPerChar, +@@ -4499,28 +4471,31 @@ doProlog(XML_Parser parser, + if (!tem) + return XML_ERROR_NO_MEMORY; + normalizePublicId(tem); +- declEntity->publicId = tem; ++ parser->m_declEntity->publicId = tem; + poolFinish(&dtd->pool); +- if (entityDeclHandler) ++ /* Don't suppress the default handler if we fell through from ++ * the XML_ROLE_DOCTYPE_PUBLIC_ID case. ++ */ ++ if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID) + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_DOCTYPE_CLOSE: +- if (doctypeName) { +- startDoctypeDeclHandler(handlerArg, doctypeName, +- doctypeSysid, doctypePubid, 0); +- poolClear(&tempPool); ++ if (parser->m_doctypeName) { ++ parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName, ++ parser->m_doctypeSysid, parser->m_doctypePubid, 0); ++ poolClear(&parser->m_tempPool); + handleDefault = XML_FALSE; + } +- /* doctypeSysid will be non-NULL in the case of a previous +- XML_ROLE_DOCTYPE_SYSTEM_ID, even if startDoctypeDeclHandler ++ /* parser->m_doctypeSysid will be non-NULL in the case of a previous ++ XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler + was not set, indicating an external subset + */ + #ifdef XML_DTD +- if (doctypeSysid || useForeignDTD) { ++ if (parser->m_doctypeSysid || parser->m_useForeignDTD) { + XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; + dtd->hasParamEntityRefs = XML_TRUE; +- if (paramEntityParsing && externalEntityRefHandler) { ++ if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) { + ENTITY *entity = (ENTITY *)lookup(parser, + &dtd->paramEntities, + externalSubsetName, +@@ -4533,10 +4508,10 @@ doProlog(XML_Parser parser, + */ + return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */ + } +- if (useForeignDTD) +- entity->base = curBase; ++ if (parser->m_useForeignDTD) ++ entity->base = parser->m_curBase; + dtd->paramEntityRead = XML_FALSE; +- if (!externalEntityRefHandler(externalEntityRefHandlerArg, ++ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, +@@ -4544,22 +4519,22 @@ doProlog(XML_Parser parser, + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; + if (dtd->paramEntityRead) { + if (!dtd->standalone && +- notStandaloneHandler && +- !notStandaloneHandler(handlerArg)) ++ parser->m_notStandaloneHandler && ++ !parser->m_notStandaloneHandler(parser->m_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) ++ else if (!parser->m_doctypeSysid) + dtd->hasParamEntityRefs = hadParamEntityRefs; + /* end of DTD - no need to update dtd->keepProcessing */ + } +- useForeignDTD = XML_FALSE; ++ parser->m_useForeignDTD = XML_FALSE; + } + #endif /* XML_DTD */ +- if (endDoctypeDeclHandler) { +- endDoctypeDeclHandler(handlerArg); ++ if (parser->m_endDoctypeDeclHandler) { ++ parser->m_endDoctypeDeclHandler(parser->m_handlerArg); + handleDefault = XML_FALSE; + } + break; +@@ -4568,18 +4543,18 @@ doProlog(XML_Parser parser, + /* if there is no DOCTYPE declaration then now is the + last chance to read the foreign DTD + */ +- if (useForeignDTD) { ++ if (parser->m_useForeignDTD) { + XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; + dtd->hasParamEntityRefs = XML_TRUE; +- if (paramEntityParsing && externalEntityRefHandler) { ++ if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) { + ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities, + externalSubsetName, + sizeof(ENTITY)); + if (!entity) + return XML_ERROR_NO_MEMORY; +- entity->base = curBase; ++ entity->base = parser->m_curBase; + dtd->paramEntityRead = XML_FALSE; +- if (!externalEntityRefHandler(externalEntityRefHandlerArg, ++ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, +@@ -4587,8 +4562,8 @@ doProlog(XML_Parser parser, + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; + if (dtd->paramEntityRead) { + if (!dtd->standalone && +- notStandaloneHandler && +- !notStandaloneHandler(handlerArg)) ++ parser->m_notStandaloneHandler && ++ !parser->m_notStandaloneHandler(parser->m_handlerArg)) + return XML_ERROR_NOT_STANDALONE; + } + /* if we didn't read the foreign DTD then this means that there +@@ -4600,55 +4575,55 @@ doProlog(XML_Parser parser, + } + } + #endif /* XML_DTD */ +- processor = contentProcessor; ++ parser->m_processor = contentProcessor; + return contentProcessor(parser, s, end, nextPtr); + case XML_ROLE_ATTLIST_ELEMENT_NAME: +- declElementType = getElementType(parser, enc, s, next); +- if (!declElementType) ++ parser->m_declElementType = getElementType(parser, enc, s, next); ++ if (!parser->m_declElementType) + return XML_ERROR_NO_MEMORY; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_NAME: +- declAttributeId = getAttributeId(parser, enc, s, next); +- if (!declAttributeId) ++ parser->m_declAttributeId = getAttributeId(parser, enc, s, next); ++ if (!parser->m_declAttributeId) + return XML_ERROR_NO_MEMORY; +- declAttributeIsCdata = XML_FALSE; +- declAttributeType = NULL; +- declAttributeIsId = XML_FALSE; ++ parser->m_declAttributeIsCdata = XML_FALSE; ++ parser->m_declAttributeType = NULL; ++ parser->m_declAttributeIsId = XML_FALSE; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_CDATA: +- declAttributeIsCdata = XML_TRUE; +- declAttributeType = atypeCDATA; ++ parser->m_declAttributeIsCdata = XML_TRUE; ++ parser->m_declAttributeType = atypeCDATA; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_ID: +- declAttributeIsId = XML_TRUE; +- declAttributeType = atypeID; ++ parser->m_declAttributeIsId = XML_TRUE; ++ parser->m_declAttributeType = atypeID; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_IDREF: +- declAttributeType = atypeIDREF; ++ parser->m_declAttributeType = atypeIDREF; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_IDREFS: +- declAttributeType = atypeIDREFS; ++ parser->m_declAttributeType = atypeIDREFS; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_ENTITY: +- declAttributeType = atypeENTITY; ++ parser->m_declAttributeType = atypeENTITY; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES: +- declAttributeType = atypeENTITIES; ++ parser->m_declAttributeType = atypeENTITIES; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN: +- declAttributeType = atypeNMTOKEN; ++ parser->m_declAttributeType = atypeNMTOKEN; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS: +- declAttributeType = atypeNMTOKENS; ++ parser->m_declAttributeType = atypeNMTOKENS; + checkAttListDeclHandler: +- if (dtd->keepProcessing && attlistDeclHandler) ++ if (dtd->keepProcessing && parser->m_attlistDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_ATTRIBUTE_ENUM_VALUE: + case XML_ROLE_ATTRIBUTE_NOTATION_VALUE: +- if (dtd->keepProcessing && attlistDeclHandler) { ++ if (dtd->keepProcessing && parser->m_attlistDeclHandler) { + const XML_Char *prefix; +- if (declAttributeType) { ++ if (parser->m_declAttributeType) { + prefix = enumValueSep; + } + else { +@@ -4656,37 +4631,37 @@ doProlog(XML_Parser parser, + ? notationPrefix + : enumValueStart); + } +- if (!poolAppendString(&tempPool, prefix)) ++ if (!poolAppendString(&parser->m_tempPool, prefix)) + return XML_ERROR_NO_MEMORY; +- if (!poolAppend(&tempPool, enc, s, next)) ++ if (!poolAppend(&parser->m_tempPool, enc, s, next)) + return XML_ERROR_NO_MEMORY; +- declAttributeType = tempPool.start; ++ parser->m_declAttributeType = parser->m_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, ++ if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId, ++ parser->m_declAttributeIsCdata, parser->m_declAttributeIsId, + 0, parser)) + return XML_ERROR_NO_MEMORY; +- if (attlistDeclHandler && declAttributeType) { +- if (*declAttributeType == XML_T(ASCII_LPAREN) +- || (*declAttributeType == XML_T(ASCII_N) +- && declAttributeType[1] == XML_T(ASCII_O))) { ++ if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { ++ if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) ++ || (*parser->m_declAttributeType == XML_T(ASCII_N) ++ && parser->m_declAttributeType[1] == XML_T(ASCII_O))) { + /* Enumerated or Notation type */ +- if (!poolAppendChar(&tempPool, XML_T(ASCII_RPAREN)) +- || !poolAppendChar(&tempPool, XML_T('\0'))) ++ if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN)) ++ || !poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_ERROR_NO_MEMORY; +- declAttributeType = tempPool.start; +- poolFinish(&tempPool); ++ parser->m_declAttributeType = parser->m_tempPool.start; ++ poolFinish(&parser->m_tempPool); + } + *eventEndPP = s; +- attlistDeclHandler(handlerArg, declElementType->name, +- declAttributeId->name, declAttributeType, ++ parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, ++ parser->m_declAttributeId->name, parser->m_declAttributeType, + 0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE); +- poolClear(&tempPool); ++ poolClear(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + } +@@ -4696,7 +4671,7 @@ doProlog(XML_Parser parser, + if (dtd->keepProcessing) { + const XML_Char *attVal; + enum XML_Error result = +- storeAttributeValue(parser, enc, declAttributeIsCdata, ++ storeAttributeValue(parser, enc, parser->m_declAttributeIsCdata, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar, + &dtd->pool); +@@ -4705,26 +4680,26 @@ doProlog(XML_Parser parser, + 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)) ++ if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId, ++ parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser)) + return XML_ERROR_NO_MEMORY; +- if (attlistDeclHandler && declAttributeType) { +- if (*declAttributeType == XML_T(ASCII_LPAREN) +- || (*declAttributeType == XML_T(ASCII_N) +- && declAttributeType[1] == XML_T(ASCII_O))) { ++ if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { ++ if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) ++ || (*parser->m_declAttributeType == XML_T(ASCII_N) ++ && parser->m_declAttributeType[1] == XML_T(ASCII_O))) { + /* Enumerated or Notation type */ +- if (!poolAppendChar(&tempPool, XML_T(ASCII_RPAREN)) +- || !poolAppendChar(&tempPool, XML_T('\0'))) ++ if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN)) ++ || !poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_ERROR_NO_MEMORY; +- declAttributeType = tempPool.start; +- poolFinish(&tempPool); ++ parser->m_declAttributeType = parser->m_tempPool.start; ++ poolFinish(&parser->m_tempPool); + } + *eventEndPP = s; +- attlistDeclHandler(handlerArg, declElementType->name, +- declAttributeId->name, declAttributeType, ++ parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, ++ parser->m_declAttributeId->name, parser->m_declAttributeType, + attVal, + role == XML_ROLE_FIXED_ATTRIBUTE_VALUE); +- poolClear(&tempPool); ++ poolClear(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + } +@@ -4734,18 +4709,18 @@ doProlog(XML_Parser parser, + 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)); ++ if (parser->m_declEntity) { ++ parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool); ++ parser->m_declEntity->textLen = (int)(poolLength(&dtd->entityValuePool)); + poolFinish(&dtd->entityValuePool); +- if (entityDeclHandler) { ++ if (parser->m_entityDeclHandler) { + *eventEndPP = s; +- entityDeclHandler(handlerArg, +- declEntity->name, +- declEntity->is_param, +- declEntity->textPtr, +- declEntity->textLen, +- curBase, 0, 0, 0); ++ parser->m_entityDeclHandler(parser->m_handlerArg, ++ parser->m_declEntity->name, ++ parser->m_declEntity->is_param, ++ parser->m_declEntity->textPtr, ++ parser->m_declEntity->textLen, ++ parser->m_curBase, 0, 0, 0); + handleDefault = XML_FALSE; + } + } +@@ -4757,97 +4732,100 @@ doProlog(XML_Parser parser, + break; + case XML_ROLE_DOCTYPE_SYSTEM_ID: + #ifdef XML_DTD +- useForeignDTD = XML_FALSE; ++ parser->m_useForeignDTD = XML_FALSE; + #endif /* XML_DTD */ + dtd->hasParamEntityRefs = XML_TRUE; +- if (startDoctypeDeclHandler) { +- doctypeSysid = poolStoreString(&tempPool, enc, ++ if (parser->m_startDoctypeDeclHandler) { ++ parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); +- if (doctypeSysid == NULL) ++ if (parser->m_doctypeSysid == NULL) + return XML_ERROR_NO_MEMORY; +- poolFinish(&tempPool); ++ poolFinish(&parser->m_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; ++ /* use externalSubsetName to make parser->m_doctypeSysid non-NULL ++ for the case where no parser->m_startDoctypeDeclHandler is set */ ++ parser->m_doctypeSysid = externalSubsetName; + #endif /* XML_DTD */ + if (!dtd->standalone + #ifdef XML_DTD +- && !paramEntityParsing ++ && !parser->m_paramEntityParsing + #endif /* XML_DTD */ +- && notStandaloneHandler +- && !notStandaloneHandler(handlerArg)) ++ && parser->m_notStandaloneHandler ++ && !parser->m_notStandaloneHandler(parser->m_handlerArg)) + return XML_ERROR_NOT_STANDALONE; + #ifndef XML_DTD + break; + #else /* XML_DTD */ +- if (!declEntity) { +- declEntity = (ENTITY *)lookup(parser, ++ if (!parser->m_declEntity) { ++ parser->m_declEntity = (ENTITY *)lookup(parser, + &dtd->paramEntities, + externalSubsetName, + sizeof(ENTITY)); +- if (!declEntity) ++ if (!parser->m_declEntity) + return XML_ERROR_NO_MEMORY; +- declEntity->publicId = NULL; ++ parser->m_declEntity->publicId = NULL; + } +- /* fall through */ + #endif /* XML_DTD */ ++ /* fall through */ + case XML_ROLE_ENTITY_SYSTEM_ID: +- if (dtd->keepProcessing && declEntity) { +- declEntity->systemId = poolStoreString(&dtd->pool, enc, ++ if (dtd->keepProcessing && parser->m_declEntity) { ++ parser->m_declEntity->systemId = poolStoreString(&dtd->pool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); +- if (!declEntity->systemId) ++ if (!parser->m_declEntity->systemId) + return XML_ERROR_NO_MEMORY; +- declEntity->base = curBase; ++ parser->m_declEntity->base = parser->m_curBase; + poolFinish(&dtd->pool); +- if (entityDeclHandler) ++ /* Don't suppress the default handler if we fell through from ++ * the XML_ROLE_DOCTYPE_SYSTEM_ID case. ++ */ ++ if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID) + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_ENTITY_COMPLETE: +- if (dtd->keepProcessing && declEntity && entityDeclHandler) { ++ if (dtd->keepProcessing && parser->m_declEntity && parser->m_entityDeclHandler) { + *eventEndPP = s; +- entityDeclHandler(handlerArg, +- declEntity->name, +- declEntity->is_param, ++ parser->m_entityDeclHandler(parser->m_handlerArg, ++ parser->m_declEntity->name, ++ parser->m_declEntity->is_param, + 0,0, +- declEntity->base, +- declEntity->systemId, +- declEntity->publicId, ++ parser->m_declEntity->base, ++ parser->m_declEntity->systemId, ++ parser->m_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) ++ if (dtd->keepProcessing && parser->m_declEntity) { ++ parser->m_declEntity->notation = poolStoreString(&dtd->pool, enc, s, next); ++ if (!parser->m_declEntity->notation) + return XML_ERROR_NO_MEMORY; + poolFinish(&dtd->pool); +- if (unparsedEntityDeclHandler) { ++ if (parser->m_unparsedEntityDeclHandler) { + *eventEndPP = s; +- unparsedEntityDeclHandler(handlerArg, +- declEntity->name, +- declEntity->base, +- declEntity->systemId, +- declEntity->publicId, +- declEntity->notation); ++ parser->m_unparsedEntityDeclHandler(parser->m_handlerArg, ++ parser->m_declEntity->name, ++ parser->m_declEntity->base, ++ parser->m_declEntity->systemId, ++ parser->m_declEntity->publicId, ++ parser->m_declEntity->notation); + handleDefault = XML_FALSE; + } +- else if (entityDeclHandler) { ++ else if (parser->m_entityDeclHandler) { + *eventEndPP = s; +- entityDeclHandler(handlerArg, +- declEntity->name, ++ parser->m_entityDeclHandler(parser->m_handlerArg, ++ parser->m_declEntity->name, + 0,0,0, +- declEntity->base, +- declEntity->systemId, +- declEntity->publicId, +- declEntity->notation); ++ parser->m_declEntity->base, ++ parser->m_declEntity->systemId, ++ parser->m_declEntity->publicId, ++ parser->m_declEntity->notation); + handleDefault = XML_FALSE; + } + } +@@ -4855,36 +4833,36 @@ doProlog(XML_Parser parser, + case XML_ROLE_GENERAL_ENTITY_NAME: + { + if (XmlPredefinedEntityName(enc, s, next)) { +- declEntity = NULL; ++ parser->m_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(parser, &dtd->generalEntities, name, ++ parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, + sizeof(ENTITY)); +- if (!declEntity) ++ if (!parser->m_declEntity) + return XML_ERROR_NO_MEMORY; +- if (declEntity->name != name) { ++ if (parser->m_declEntity->name != name) { + poolDiscard(&dtd->pool); +- declEntity = NULL; ++ parser->m_declEntity = NULL; + } + else { + poolFinish(&dtd->pool); +- declEntity->publicId = NULL; +- declEntity->is_param = XML_FALSE; ++ parser->m_declEntity->publicId = NULL; ++ parser->m_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) ++ parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities); ++ if (parser->m_entityDeclHandler) + handleDefault = XML_FALSE; + } + } + else { + poolDiscard(&dtd->pool); +- declEntity = NULL; ++ parser->m_declEntity = NULL; + } + } + break; +@@ -4894,90 +4872,90 @@ doProlog(XML_Parser parser, + const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next); + if (!name) + return XML_ERROR_NO_MEMORY; +- declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities, ++ parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities, + name, sizeof(ENTITY)); +- if (!declEntity) ++ if (!parser->m_declEntity) + return XML_ERROR_NO_MEMORY; +- if (declEntity->name != name) { ++ if (parser->m_declEntity->name != name) { + poolDiscard(&dtd->pool); +- declEntity = NULL; ++ parser->m_declEntity = NULL; + } + else { + poolFinish(&dtd->pool); +- declEntity->publicId = NULL; +- declEntity->is_param = XML_TRUE; ++ parser->m_declEntity->publicId = NULL; ++ parser->m_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) ++ parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities); ++ if (parser->m_entityDeclHandler) + handleDefault = XML_FALSE; + } + } + else { + poolDiscard(&dtd->pool); +- declEntity = NULL; ++ parser->m_declEntity = NULL; + } + #else /* not XML_DTD */ +- declEntity = NULL; ++ parser->m_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) ++ parser->m_declNotationPublicId = NULL; ++ parser->m_declNotationName = NULL; ++ if (parser->m_notationDeclHandler) { ++ parser->m_declNotationName = poolStoreString(&parser->m_tempPool, enc, s, next); ++ if (!parser->m_declNotationName) + return XML_ERROR_NO_MEMORY; +- poolFinish(&tempPool); ++ poolFinish(&parser->m_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, ++ if (parser->m_declNotationName) { /* means m_notationDeclHandler != NULL */ ++ XML_Char *tem = poolStoreString(&parser->m_tempPool, + enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!tem) + return XML_ERROR_NO_MEMORY; + normalizePublicId(tem); +- declNotationPublicId = tem; +- poolFinish(&tempPool); ++ parser->m_declNotationPublicId = tem; ++ poolFinish(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_NOTATION_SYSTEM_ID: +- if (declNotationName && notationDeclHandler) { ++ if (parser->m_declNotationName && parser->m_notationDeclHandler) { + const XML_Char *systemId +- = poolStoreString(&tempPool, enc, ++ = poolStoreString(&parser->m_tempPool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!systemId) + return XML_ERROR_NO_MEMORY; + *eventEndPP = s; +- notationDeclHandler(handlerArg, +- declNotationName, +- curBase, ++ parser->m_notationDeclHandler(parser->m_handlerArg, ++ parser->m_declNotationName, ++ parser->m_curBase, + systemId, +- declNotationPublicId); ++ parser->m_declNotationPublicId); + handleDefault = XML_FALSE; + } +- poolClear(&tempPool); ++ poolClear(&parser->m_tempPool); + break; + case XML_ROLE_NOTATION_NO_SYSTEM_ID: +- if (declNotationPublicId && notationDeclHandler) { ++ if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) { + *eventEndPP = s; +- notationDeclHandler(handlerArg, +- declNotationName, +- curBase, ++ parser->m_notationDeclHandler(parser->m_handlerArg, ++ parser->m_declNotationName, ++ parser->m_curBase, + 0, +- declNotationPublicId); ++ parser->m_declNotationPublicId); + handleDefault = XML_FALSE; + } +- poolClear(&tempPool); ++ poolClear(&parser->m_tempPool); + break; + case XML_ROLE_ERROR: + switch (tok) { +@@ -4994,45 +4972,45 @@ doProlog(XML_Parser parser, + case XML_ROLE_IGNORE_SECT: + { + enum XML_Error result; +- if (defaultHandler) ++ if (parser->m_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; ++ parser->m_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 (parser->m_prologState.level >= parser->m_groupSize) { ++ if (parser->m_groupSize) { ++ char *temp = (char *)REALLOC(parser, parser->m_groupConnector, parser->m_groupSize *= 2); + if (temp == NULL) { +- groupSize /= 2; ++ parser->m_groupSize /= 2; + return XML_ERROR_NO_MEMORY; + } +- groupConnector = temp; ++ parser->m_groupConnector = temp; + if (dtd->scaffIndex) { +- int *temp = (int *)REALLOC(dtd->scaffIndex, +- groupSize * sizeof(int)); ++ int *temp = (int *)REALLOC(parser, dtd->scaffIndex, ++ parser->m_groupSize * sizeof(int)); + if (temp == NULL) + return XML_ERROR_NO_MEMORY; + dtd->scaffIndex = temp; + } + } + else { +- groupConnector = (char *)MALLOC(groupSize = 32); +- if (!groupConnector) { +- groupSize = 0; ++ parser->m_groupConnector = (char *)MALLOC(parser, parser->m_groupSize = 32); ++ if (!parser->m_groupConnector) { ++ parser->m_groupSize = 0; + return XML_ERROR_NO_MEMORY; + } + } + } +- groupConnector[prologState.level] = 0; ++ parser->m_groupConnector[parser->m_prologState.level] = 0; + if (dtd->in_eldecl) { + int myindex = nextScaffoldPart(parser); + if (myindex < 0) +@@ -5040,37 +5018,37 @@ doProlog(XML_Parser parser, + dtd->scaffIndex[dtd->scaffLevel] = myindex; + dtd->scaffLevel++; + dtd->scaffold[myindex].type = XML_CTYPE_SEQ; +- if (elementDeclHandler) ++ if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_GROUP_SEQUENCE: +- if (groupConnector[prologState.level] == ASCII_PIPE) ++ if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE) + return XML_ERROR_SYNTAX; +- groupConnector[prologState.level] = ASCII_COMMA; +- if (dtd->in_eldecl && elementDeclHandler) ++ parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA; ++ if (dtd->in_eldecl && parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_GROUP_CHOICE: +- if (groupConnector[prologState.level] == ASCII_COMMA) ++ if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA) + return XML_ERROR_SYNTAX; + if (dtd->in_eldecl +- && !groupConnector[prologState.level] ++ && !parser->m_groupConnector[parser->m_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) ++ if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + } +- groupConnector[prologState.level] = ASCII_PIPE; ++ parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE; + break; + case XML_ROLE_PARAM_ENTITY_REF: + #ifdef XML_DTD + case XML_ROLE_INNER_PARAM_ENTITY_REF: + dtd->hasParamEntityRefs = XML_TRUE; +- if (!paramEntityParsing) ++ if (!parser->m_paramEntityParsing) + dtd->keepProcessing = dtd->standalone; + else { + const XML_Char *name; +@@ -5086,9 +5064,9 @@ doProlog(XML_Parser parser, + if yes, check that the entity exists, and that it is internal, + otherwise call the skipped entity handler + */ +- if (prologState.documentEntity && ++ if (parser->m_prologState.documentEntity && + (dtd->standalone +- ? !openInternalEntities ++ ? !parser->m_openInternalEntities + : !dtd->hasParamEntityRefs)) { + if (!entity) + return XML_ERROR_UNDEFINED_ENTITY; +@@ -5119,8 +5097,8 @@ doProlog(XML_Parser parser, + 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); ++ if ((role == XML_ROLE_PARAM_ENTITY_REF) && parser->m_skippedEntityHandler) { ++ parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1); + handleDefault = XML_FALSE; + } + break; +@@ -5137,10 +5115,10 @@ doProlog(XML_Parser parser, + handleDefault = XML_FALSE; + break; + } +- if (externalEntityRefHandler) { ++ if (parser->m_externalEntityRefHandler) { + dtd->paramEntityRead = XML_FALSE; + entity->open = XML_TRUE; +- if (!externalEntityRefHandler(externalEntityRefHandlerArg, ++ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, +@@ -5162,17 +5140,17 @@ doProlog(XML_Parser parser, + } + #endif /* XML_DTD */ + if (!dtd->standalone && +- notStandaloneHandler && +- !notStandaloneHandler(handlerArg)) ++ parser->m_notStandaloneHandler && ++ !parser->m_notStandaloneHandler(parser->m_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) ++ if (parser->m_elementDeclHandler) { ++ parser->m_declElementType = getElementType(parser, enc, s, next); ++ if (!parser->m_declElementType) + return XML_ERROR_NO_MEMORY; + dtd->scaffLevel = 0; + dtd->scaffCount = 0; +@@ -5184,8 +5162,8 @@ doProlog(XML_Parser parser, + 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 (parser->m_elementDeclHandler) { ++ XML_Content * content = (XML_Content *) MALLOC(parser, sizeof(XML_Content)); + if (!content) + return XML_ERROR_NO_MEMORY; + content->quant = XML_CQUANT_NONE; +@@ -5196,7 +5174,7 @@ doProlog(XML_Parser parser, + XML_CTYPE_ANY : + XML_CTYPE_EMPTY); + *eventEndPP = s; +- elementDeclHandler(handlerArg, declElementType->name, content); ++ parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, content); + handleDefault = XML_FALSE; + } + dtd->in_eldecl = XML_FALSE; +@@ -5207,7 +5185,7 @@ doProlog(XML_Parser parser, + if (dtd->in_eldecl) { + dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type + = XML_CTYPE_MIXED; +- if (elementDeclHandler) ++ if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + } + break; +@@ -5244,7 +5222,7 @@ doProlog(XML_Parser parser, + nameLen = 0; + for (; name[nameLen++]; ); + dtd->contentStringLen += nameLen; +- if (elementDeclHandler) ++ if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + } + break; +@@ -5262,7 +5240,7 @@ doProlog(XML_Parser parser, + quant = XML_CQUANT_PLUS; + closeGroup: + if (dtd->in_eldecl) { +- if (elementDeclHandler) ++ if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + dtd->scaffLevel--; + dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant; +@@ -5272,7 +5250,7 @@ doProlog(XML_Parser parser, + if (!model) + return XML_ERROR_NO_MEMORY; + *eventEndPP = s; +- elementDeclHandler(handlerArg, declElementType->name, model); ++ parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, model); + } + dtd->in_eldecl = XML_FALSE; + dtd->contentStringLen = 0; +@@ -5299,31 +5277,31 @@ doProlog(XML_Parser parser, + } + break; + case XML_ROLE_DOCTYPE_NONE: +- if (startDoctypeDeclHandler) ++ if (parser->m_startDoctypeDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_ENTITY_NONE: +- if (dtd->keepProcessing && entityDeclHandler) ++ if (dtd->keepProcessing && parser->m_entityDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_NOTATION_NONE: +- if (notationDeclHandler) ++ if (parser->m_notationDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_ATTLIST_NONE: +- if (dtd->keepProcessing && attlistDeclHandler) ++ if (dtd->keepProcessing && parser->m_attlistDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_ELEMENT_NONE: +- if (elementDeclHandler) ++ if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + break; + } /* end of big switch */ + +- if (handleDefault && defaultHandler) ++ if (handleDefault && parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + +- switch (ps_parsing) { ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *nextPtr = next; + return XML_ERROR_NONE; +@@ -5343,18 +5321,18 @@ epilogProcessor(XML_Parser parser, + const char *end, + const char **nextPtr) + { +- processor = epilogProcessor; +- eventPtr = s; ++ parser->m_processor = epilogProcessor; ++ parser->m_eventPtr = s; + for (;;) { + const char *next = NULL; +- int tok = XmlPrologTok(encoding, s, end, &next); +- eventEndPtr = next; ++ int tok = XmlPrologTok(parser->m_encoding, s, end, &next); ++ parser->m_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) ++ if (parser->m_defaultHandler) { ++ reportDefault(parser, parser->m_encoding, s, next); ++ if (parser->m_parsingStatus.parsing == XML_FINISHED) + return XML_ERROR_ABORTED; + } + *nextPtr = next; +@@ -5363,28 +5341,28 @@ epilogProcessor(XML_Parser parser, + *nextPtr = s; + return XML_ERROR_NONE; + case XML_TOK_PROLOG_S: +- if (defaultHandler) +- reportDefault(parser, encoding, s, next); ++ if (parser->m_defaultHandler) ++ reportDefault(parser, parser->m_encoding, s, next); + break; + case XML_TOK_PI: +- if (!reportProcessingInstruction(parser, encoding, s, next)) ++ if (!reportProcessingInstruction(parser, parser->m_encoding, s, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_COMMENT: +- if (!reportComment(parser, encoding, s, next)) ++ if (!reportComment(parser, parser->m_encoding, s, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_INVALID: +- eventPtr = next; ++ parser->m_eventPtr = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: +- if (!ps_finalBuffer) { ++ if (!parser->m_parsingStatus.finalBuffer) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: +- if (!ps_finalBuffer) { ++ if (!parser->m_parsingStatus.finalBuffer) { + *nextPtr = s; + return XML_ERROR_NONE; + } +@@ -5392,8 +5370,8 @@ epilogProcessor(XML_Parser parser, + default: + return XML_ERROR_JUNK_AFTER_DOC_ELEMENT; + } +- eventPtr = s = next; +- switch (ps_parsing) { ++ parser->m_eventPtr = s = next; ++ switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *nextPtr = next; + return XML_ERROR_NONE; +@@ -5413,21 +5391,21 @@ processInternalEntity(XML_Parser parser, ENTITY *entity, + enum XML_Error result; + OPEN_INTERNAL_ENTITY *openEntity; + +- if (freeInternalEntities) { +- openEntity = freeInternalEntities; +- freeInternalEntities = openEntity->next; ++ if (parser->m_freeInternalEntities) { ++ openEntity = parser->m_freeInternalEntities; ++ parser->m_freeInternalEntities = openEntity->next; + } + else { +- openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(sizeof(OPEN_INTERNAL_ENTITY)); ++ openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY)); + if (!openEntity) + return XML_ERROR_NO_MEMORY; + } + entity->open = XML_TRUE; + entity->processed = 0; +- openEntity->next = openInternalEntities; +- openInternalEntities = openEntity; ++ openEntity->next = parser->m_openInternalEntities; ++ parser->m_openInternalEntities = openEntity; + openEntity->entity = entity; +- openEntity->startTagLevel = tagLevel; ++ openEntity->startTagLevel = parser->m_tagLevel; + openEntity->betweenDecl = betweenDecl; + openEntity->internalEventPtr = NULL; + openEntity->internalEventEndPtr = NULL; +@@ -5438,26 +5416,26 @@ processInternalEntity(XML_Parser parser, ENTITY *entity, + + #ifdef XML_DTD + if (entity->is_param) { +- int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next); +- result = doProlog(parser, internalEncoding, textStart, textEnd, tok, ++ int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); ++ result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, + next, &next, XML_FALSE); + } + else + #endif /* XML_DTD */ +- result = doContent(parser, tagLevel, internalEncoding, textStart, ++ result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, textStart, + textEnd, &next, XML_FALSE); + + if (result == XML_ERROR_NONE) { +- if (textEnd != next && ps_parsing == XML_SUSPENDED) { ++ if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { + entity->processed = (int)(next - textStart); +- processor = internalEntityProcessor; ++ parser->m_processor = internalEntityProcessor; + } + else { + entity->open = XML_FALSE; +- openInternalEntities = openEntity->next; ++ parser->m_openInternalEntities = openEntity->next; + /* put openEntity back in list of free instances */ +- openEntity->next = freeInternalEntities; +- freeInternalEntities = openEntity; ++ openEntity->next = parser->m_freeInternalEntities; ++ parser->m_freeInternalEntities = openEntity; + } + } + return result; +@@ -5473,7 +5451,7 @@ internalEntityProcessor(XML_Parser parser, + const char *textStart, *textEnd; + const char *next; + enum XML_Error result; +- OPEN_INTERNAL_ENTITY *openEntity = openInternalEntities; ++ OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities; + if (!openEntity) + return XML_ERROR_UNEXPECTED_STATE; + +@@ -5485,44 +5463,44 @@ internalEntityProcessor(XML_Parser parser, + + #ifdef XML_DTD + if (entity->is_param) { +- int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next); +- result = doProlog(parser, internalEncoding, textStart, textEnd, tok, ++ int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); ++ result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, + next, &next, XML_FALSE); + } + else + #endif /* XML_DTD */ +- result = doContent(parser, openEntity->startTagLevel, internalEncoding, ++ result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding, + textStart, textEnd, &next, XML_FALSE); + + if (result != XML_ERROR_NONE) + return result; +- else if (textEnd != next && ps_parsing == XML_SUSPENDED) { ++ else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { + entity->processed = (int)(next - (char *)entity->textPtr); + return result; + } + else { + entity->open = XML_FALSE; +- openInternalEntities = openEntity->next; ++ parser->m_openInternalEntities = openEntity->next; + /* put openEntity back in list of free instances */ +- openEntity->next = freeInternalEntities; +- freeInternalEntities = openEntity; ++ openEntity->next = parser->m_freeInternalEntities; ++ parser->m_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); ++ parser->m_processor = prologProcessor; ++ tok = XmlPrologTok(parser->m_encoding, s, end, &next); ++ return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, ++ (XML_Bool)!parser->m_parsingStatus.finalBuffer); + } + else + #endif /* XML_DTD */ + { +- processor = contentProcessor; ++ parser->m_processor = contentProcessor; + /* see externalEntityContentProcessor vs contentProcessor */ +- return doContent(parser, parentParser ? 1 : 0, encoding, s, end, +- nextPtr, (XML_Bool)!ps_finalBuffer); ++ return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end, ++ nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + } + } + +@@ -5532,7 +5510,7 @@ errorProcessor(XML_Parser parser, + const char *UNUSED_P(end), + const char **UNUSED_P(nextPtr)) + { +- return errorCode; ++ return parser->m_errorCode; + } + + static enum XML_Error +@@ -5556,7 +5534,7 @@ 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 */ ++ DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + for (;;) { + const char *next; + int tok = XmlAttributeValueTok(enc, ptr, end, &next); +@@ -5564,12 +5542,12 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, + case XML_TOK_NONE: + return XML_ERROR_NONE; + case XML_TOK_INVALID: +- if (enc == encoding) +- eventPtr = next; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: +- if (enc == encoding) +- eventPtr = ptr; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = ptr; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_CHAR_REF: + { +@@ -5577,8 +5555,8 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, + int i; + int n = XmlCharRefNumber(enc, ptr); + if (n < 0) { +- if (enc == encoding) +- eventPtr = ptr; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = ptr; + return XML_ERROR_BAD_CHAR_REF; + } + if (!isCdata +@@ -5628,25 +5606,25 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, + return XML_ERROR_NO_MEMORY; + break; + } +- name = poolStoreString(&temp2Pool, enc, ++ name = poolStoreString(&parser->m_temp2Pool, enc, + ptr + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) + return XML_ERROR_NO_MEMORY; + entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0); +- poolDiscard(&temp2Pool); ++ poolDiscard(&parser->m_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 && ++ parser->m_prologState.documentEntity && + #endif /* XML_DTD */ + (dtd->standalone +- ? !openInternalEntities ++ ? !parser->m_openInternalEntities + : !dtd->hasParamEntityRefs); +- else /* if (pool == &tempPool): we are called from content */ ++ else /* if (pool == &parser->m_tempPool): we are called from content */ + checkEntityDecl = !dtd->hasParamEntityRefs || dtd->standalone; + if (checkEntityDecl) { + if (!entity) +@@ -5656,19 +5634,19 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, + } + else if (!entity) { + /* Cannot report skipped entity here - see comments on +- skippedEntityHandler. +- if (skippedEntityHandler) +- skippedEntityHandler(handlerArg, name, 0); ++ parser->m_skippedEntityHandler. ++ if (parser->m_skippedEntityHandler) ++ parser->m_skippedEntityHandler(parser->m_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) ++ if ((pool == &parser->m_tempPool) && parser->m_defaultHandler) + reportDefault(parser, enc, ptr, next); + */ + break; + } + if (entity->open) { +- if (enc == encoding) { ++ if (enc == parser->m_encoding) { + /* It does not appear that this line can be executed. + * + * The "if (entity->open)" check catches recursive entity +@@ -5686,25 +5664,25 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, + * we keep the line and merely exclude it from coverage + * tests. + */ +- eventPtr = ptr; /* LCOV_EXCL_LINE */ ++ parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */ + } + return XML_ERROR_RECURSIVE_ENTITY_REF; + } + if (entity->notation) { +- if (enc == encoding) +- eventPtr = ptr; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = ptr; + return XML_ERROR_BINARY_ENTITY_REF; + } + if (!entity->textPtr) { +- if (enc == encoding) +- eventPtr = ptr; ++ if (enc == parser->m_encoding) ++ parser->m_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, ++ result = appendAttributeValue(parser, parser->m_internalEncoding, isCdata, + (char *)entity->textPtr, + (char *)textEnd, pool); + entity->open = XML_FALSE; +@@ -5725,8 +5703,8 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, + * + * LCOV_EXCL_START + */ +- if (enc == encoding) +- eventPtr = ptr; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = ptr; + return XML_ERROR_UNEXPECTED_STATE; + /* LCOV_EXCL_STOP */ + } +@@ -5741,12 +5719,12 @@ storeEntityValue(XML_Parser parser, + const char *entityTextPtr, + const char *entityTextEnd) + { +- DTD * const dtd = _dtd; /* save one level of indirection */ ++ DTD * const dtd = parser->m_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; ++ int oldInEntityValue = parser->m_prologState.inEntityValue; ++ parser->m_prologState.inEntityValue = 1; + #endif /* XML_DTD */ + /* never return Null for the value argument in EntityDeclHandler, + since this would indicate an external entity; therefore we +@@ -5762,10 +5740,10 @@ storeEntityValue(XML_Parser parser, + switch (tok) { + case XML_TOK_PARAM_ENTITY_REF: + #ifdef XML_DTD +- if (isParamEntity || enc != encoding) { ++ if (parser->m_isParamEntity || enc != parser->m_encoding) { + const XML_Char *name; + ENTITY *entity; +- name = poolStoreString(&tempPool, enc, ++ name = poolStoreString(&parser->m_tempPool, enc, + entityTextPtr + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) { +@@ -5773,28 +5751,28 @@ storeEntityValue(XML_Parser parser, + goto endEntityValue; + } + entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0); +- poolDiscard(&tempPool); ++ poolDiscard(&parser->m_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); ++ parser->m_skippedEntityHandler ++ if (parser->m_skippedEntityHandler) ++ parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0); + */ + dtd->keepProcessing = dtd->standalone; + goto endEntityValue; + } + if (entity->open) { +- if (enc == encoding) +- eventPtr = entityTextPtr; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_RECURSIVE_ENTITY_REF; + goto endEntityValue; + } + if (entity->systemId) { +- if (externalEntityRefHandler) { ++ if (parser->m_externalEntityRefHandler) { + dtd->paramEntityRead = XML_FALSE; + entity->open = XML_TRUE; +- if (!externalEntityRefHandler(externalEntityRefHandlerArg, ++ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, +@@ -5813,7 +5791,7 @@ storeEntityValue(XML_Parser parser, + else { + entity->open = XML_TRUE; + result = storeEntityValue(parser, +- internalEncoding, ++ parser->m_internalEncoding, + (char *)entity->textPtr, + (char *)(entity->textPtr + + entity->textLen)); +@@ -5826,7 +5804,7 @@ storeEntityValue(XML_Parser parser, + #endif /* XML_DTD */ + /* In the internal subset, PE references are not legal + within markup declarations, e.g entity values in this case. */ +- eventPtr = entityTextPtr; ++ parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_PARAM_ENTITY_REF; + goto endEntityValue; + case XML_TOK_NONE: +@@ -5855,8 +5833,8 @@ storeEntityValue(XML_Parser parser, + int i; + int n = XmlCharRefNumber(enc, entityTextPtr); + if (n < 0) { +- if (enc == encoding) +- eventPtr = entityTextPtr; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_BAD_CHAR_REF; + goto endEntityValue; + } +@@ -5880,13 +5858,13 @@ storeEntityValue(XML_Parser parser, + } + break; + case XML_TOK_PARTIAL: +- if (enc == encoding) +- eventPtr = entityTextPtr; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_INVALID_TOKEN; + goto endEntityValue; + case XML_TOK_INVALID: +- if (enc == encoding) +- eventPtr = next; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = next; + result = XML_ERROR_INVALID_TOKEN; + goto endEntityValue; + default: +@@ -5897,8 +5875,8 @@ storeEntityValue(XML_Parser parser, + * + * LCOV_EXCL_START + */ +- if (enc == encoding) +- eventPtr = entityTextPtr; ++ if (enc == parser->m_encoding) ++ parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_UNEXPECTED_STATE; + goto endEntityValue; + /* LCOV_EXCL_STOP */ +@@ -5907,7 +5885,7 @@ storeEntityValue(XML_Parser parser, + } + endEntityValue: + #ifdef XML_DTD +- prologState.inEntityValue = oldInEntityValue; ++ parser->m_prologState.inEntityValue = oldInEntityValue; + #endif /* XML_DTD */ + return result; + } +@@ -5942,25 +5920,25 @@ reportProcessingInstruction(XML_Parser parser, const ENCODING *enc, + const XML_Char *target; + XML_Char *data; + const char *tem; +- if (!processingInstructionHandler) { +- if (defaultHandler) ++ if (!parser->m_processingInstructionHandler) { ++ if (parser->m_defaultHandler) + reportDefault(parser, enc, start, end); + return 1; + } + start += enc->minBytesPerChar * 2; + tem = start + XmlNameLength(enc, start); +- target = poolStoreString(&tempPool, enc, start, tem); ++ target = poolStoreString(&parser->m_tempPool, enc, start, tem); + if (!target) + return 0; +- poolFinish(&tempPool); +- data = poolStoreString(&tempPool, enc, ++ poolFinish(&parser->m_tempPool); ++ data = poolStoreString(&parser->m_tempPool, enc, + XmlSkipS(enc, tem), + end - enc->minBytesPerChar*2); + if (!data) + return 0; + normalizeLines(data); +- processingInstructionHandler(handlerArg, target, data); +- poolClear(&tempPool); ++ parser->m_processingInstructionHandler(parser->m_handlerArg, target, data); ++ poolClear(&parser->m_tempPool); + return 1; + } + +@@ -5969,20 +5947,20 @@ reportComment(XML_Parser parser, const ENCODING *enc, + const char *start, const char *end) + { + XML_Char *data; +- if (!commentHandler) { +- if (defaultHandler) ++ if (!parser->m_commentHandler) { ++ if (parser->m_defaultHandler) + reportDefault(parser, enc, start, end); + return 1; + } +- data = poolStoreString(&tempPool, ++ data = poolStoreString(&parser->m_tempPool, + enc, + start + enc->minBytesPerChar * 4, + end - enc->minBytesPerChar * 3); + if (!data) + return 0; + normalizeLines(data); +- commentHandler(handlerArg, data); +- poolClear(&tempPool); ++ parser->m_commentHandler(parser->m_handlerArg, data); ++ poolClear(&parser->m_tempPool); + return 1; + } + +@@ -5994,9 +5972,9 @@ reportDefault(XML_Parser parser, const ENCODING *enc, + enum XML_Convert_Result convert_res; + const char **eventPP; + const char **eventEndPP; +- if (enc == encoding) { +- eventPP = &eventPtr; +- eventEndPP = &eventEndPtr; ++ if (enc == parser->m_encoding) { ++ eventPP = &parser->m_eventPtr; ++ eventEndPP = &parser->m_eventEndPtr; + } + else { + /* To get here, two things must be true; the parser must be +@@ -6015,20 +5993,20 @@ reportDefault(XML_Parser parser, const ENCODING *enc, + * + * LCOV_EXCL_START + */ +- eventPP = &(openInternalEntities->internalEventPtr); +- eventEndPP = &(openInternalEntities->internalEventEndPtr); ++ eventPP = &(parser->m_openInternalEntities->internalEventPtr); ++ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + /* LCOV_EXCL_STOP */ + } + do { +- ICHAR *dataPtr = (ICHAR *)dataBuf; +- convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd); ++ ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf; ++ convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd); + *eventEndPP = s; +- defaultHandler(handlerArg, dataBuf, (int)(dataPtr - (ICHAR *)dataBuf)); ++ parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf, (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + *eventPP = s; + } while ((convert_res != XML_CONVERT_COMPLETED) && (convert_res != XML_CONVERT_INPUT_INCOMPLETE)); + } + else +- defaultHandler(handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s)); ++ parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s)); + } + + +@@ -6050,16 +6028,18 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata, + if (type->nDefaultAtts == type->allocDefaultAtts) { + if (type->allocDefaultAtts == 0) { + type->allocDefaultAtts = 8; +- type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(type->allocDefaultAtts ++ type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(parser, type->allocDefaultAtts + * sizeof(DEFAULT_ATTRIBUTE)); +- if (!type->defaultAtts) ++ if (!type->defaultAtts) { ++ type->allocDefaultAtts = 0; + return 0; ++ } + } + else { + DEFAULT_ATTRIBUTE *temp; + int count = type->allocDefaultAtts * 2; + temp = (DEFAULT_ATTRIBUTE *) +- REALLOC(type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE))); ++ REALLOC(parser, type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE))); + if (temp == NULL) + return 0; + type->allocDefaultAtts = count; +@@ -6079,7 +6059,7 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata, + static int + setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) + { +- DTD * const dtd = _dtd; /* save one level of indirection */ ++ DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + const XML_Char *name; + for (name = elementType->name; *name; name++) { + if (*name == XML_T(ASCII_COLON)) { +@@ -6110,7 +6090,7 @@ 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 */ ++ DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + ATTRIBUTE_ID *id; + const XML_Char *name; + if (!poolAppendChar(&dtd->pool, XML_T('\0'))) +@@ -6127,7 +6107,7 @@ getAttributeId(XML_Parser parser, const ENCODING *enc, + poolDiscard(&dtd->pool); + else { + poolFinish(&dtd->pool); +- if (!ns) ++ if (!parser->m_ns) + ; + else if (name[0] == XML_T(ASCII_x) + && name[1] == XML_T(ASCII_m) +@@ -6174,20 +6154,20 @@ getAttributeId(XML_Parser parser, const ENCODING *enc, + static const XML_Char * + getContext(XML_Parser parser) + { +- DTD * const dtd = _dtd; /* save one level of indirection */ ++ DTD * const dtd = parser->m_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(ASCII_EQUALS))) ++ if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS))) + return NULL; + len = dtd->defaultPrefix.binding->uriLen; +- if (namespaceSeparator) ++ if (parser->m_namespaceSeparator) + len--; + for (i = 0; i < len; i++) { +- if (!poolAppendChar(&tempPool, dtd->defaultPrefix.binding->uri[i])) { ++ if (!poolAppendChar(&parser->m_tempPool, dtd->defaultPrefix.binding->uri[i])) { + /* Because of memory caching, I don't believe this line can be + * executed. + * +@@ -6230,18 +6210,18 @@ getContext(XML_Parser parser) + */ + continue; /* LCOV_EXCL_LINE */ + } +- if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP)) ++ if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP)) + return NULL; + for (s = prefix->name; *s; s++) +- if (!poolAppendChar(&tempPool, *s)) ++ if (!poolAppendChar(&parser->m_tempPool, *s)) + return NULL; +- if (!poolAppendChar(&tempPool, XML_T(ASCII_EQUALS))) ++ if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS))) + return NULL; + len = prefix->binding->uriLen; +- if (namespaceSeparator) ++ if (parser->m_namespaceSeparator) + len--; + for (i = 0; i < len; i++) +- if (!poolAppendChar(&tempPool, prefix->binding->uri[i])) ++ if (!poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i])) + return NULL; + needSep = XML_TRUE; + } +@@ -6255,73 +6235,73 @@ getContext(XML_Parser parser) + break; + if (!e->open) + continue; +- if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP)) ++ if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP)) + return NULL; + for (s = e->name; *s; s++) +- if (!poolAppendChar(&tempPool, *s)) ++ if (!poolAppendChar(&parser->m_tempPool, *s)) + return 0; + needSep = XML_TRUE; + } + +- if (!poolAppendChar(&tempPool, XML_T('\0'))) ++ if (!poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return NULL; +- return tempPool.start; ++ return parser->m_tempPool.start; + } + + static XML_Bool + setContext(XML_Parser parser, const XML_Char *context) + { +- DTD * const dtd = _dtd; /* save one level of indirection */ ++ DTD * const dtd = parser->m_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'))) ++ if (!poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_FALSE; +- e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&tempPool), 0); ++ e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&parser->m_tempPool), 0); + if (e) + e->open = XML_TRUE; + if (*s != XML_T('\0')) + s++; + context = s; +- poolDiscard(&tempPool); ++ poolDiscard(&parser->m_tempPool); + } + else if (*s == XML_T(ASCII_EQUALS)) { + PREFIX *prefix; +- if (poolLength(&tempPool) == 0) ++ if (poolLength(&parser->m_tempPool) == 0) + prefix = &dtd->defaultPrefix; + else { +- if (!poolAppendChar(&tempPool, XML_T('\0'))) ++ if (!poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_FALSE; +- prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&tempPool), ++ prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&parser->m_tempPool), + sizeof(PREFIX)); + if (!prefix) + return XML_FALSE; +- if (prefix->name == poolStart(&tempPool)) { ++ if (prefix->name == poolStart(&parser->m_tempPool)) { + prefix->name = poolCopyString(&dtd->pool, prefix->name); + if (!prefix->name) + return XML_FALSE; + } +- poolDiscard(&tempPool); ++ poolDiscard(&parser->m_tempPool); + } + for (context = s + 1; + *context != CONTEXT_SEP && *context != XML_T('\0'); + context++) +- if (!poolAppendChar(&tempPool, *context)) ++ if (!poolAppendChar(&parser->m_tempPool, *context)) + return XML_FALSE; +- if (!poolAppendChar(&tempPool, XML_T('\0'))) ++ if (!poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_FALSE; +- if (addBinding(parser, prefix, NULL, poolStart(&tempPool), +- &inheritedBindings) != XML_ERROR_NONE) ++ if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool), ++ &parser->m_inheritedBindings) != XML_ERROR_NONE) + return XML_FALSE; +- poolDiscard(&tempPool); ++ poolDiscard(&parser->m_tempPool); + if (*context != XML_T('\0')) + ++context; + s = context; + } + else { +- if (!poolAppendChar(&tempPool, *s)) ++ if (!poolAppendChar(&parser->m_tempPool, *s)) + return XML_FALSE; + s++; + } +@@ -6686,7 +6666,6 @@ hash(XML_Parser parser, KEY s) + { + struct siphash state; + struct sipkey key; +- (void)sip_tobin; + (void)sip24_valid; + copy_salt_to_sipkey(parser, &key); + sip24_init(&state, &key); +@@ -7006,8 +6985,8 @@ poolGrow(STRING_POOL *pool) + int blockSize = (int)((unsigned)(pool->end - pool->start)*2U); + size_t bytesToAllocate; + +- // NOTE: Needs to be calculated prior to calling `realloc` +- // to avoid dangling pointers: ++ /* NOTE: Needs to be calculated prior to calling `realloc` ++ to avoid dangling pointers: */ + const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start; + + if (blockSize < 0) { +@@ -7085,12 +7064,12 @@ poolGrow(STRING_POOL *pool) + static int FASTCALL + nextScaffoldPart(XML_Parser parser) + { +- DTD * const dtd = _dtd; /* save one level of indirection */ ++ DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + CONTENT_SCAFFOLD * me; + int next; + + if (!dtd->scaffIndex) { +- dtd->scaffIndex = (int *)MALLOC(groupSize * sizeof(int)); ++ dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int)); + if (!dtd->scaffIndex) + return -1; + dtd->scaffIndex[0] = 0; +@@ -7100,13 +7079,13 @@ nextScaffoldPart(XML_Parser parser) + CONTENT_SCAFFOLD *temp; + if (dtd->scaffold) { + temp = (CONTENT_SCAFFOLD *) +- REALLOC(dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD)); ++ REALLOC(parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD)); + if (temp == NULL) + return -1; + dtd->scaffSize *= 2; + } + else { +- temp = (CONTENT_SCAFFOLD *)MALLOC(INIT_SCAFFOLD_ELEMENTS ++ temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS + * sizeof(CONTENT_SCAFFOLD)); + if (temp == NULL) + return -1; +@@ -7137,7 +7116,7 @@ build_node(XML_Parser parser, + XML_Content **contpos, + XML_Char **strpos) + { +- DTD * const dtd = _dtd; /* save one level of indirection */ ++ DTD * const dtd = parser->m_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) { +@@ -7171,14 +7150,14 @@ build_node(XML_Parser parser, + static XML_Content * + build_model (XML_Parser parser) + { +- DTD * const dtd = _dtd; /* save one level of indirection */ ++ DTD * const dtd = parser->m_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); ++ ret = (XML_Content *)MALLOC(parser, allocsize); + if (!ret) + return NULL; + +@@ -7195,7 +7174,7 @@ getElementType(XML_Parser parser, + const char *ptr, + const char *end) + { +- DTD * const dtd = _dtd; /* save one level of indirection */ ++ DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end); + ELEMENT_TYPE *ret; + +diff --git a/Modules/expat/xmltok.c b/Modules/expat/xmltok.c +index 482df75b20..6b415d8397 100644 +--- a/Modules/expat/xmltok.c ++++ b/Modules/expat/xmltok.c +@@ -31,7 +31,7 @@ + */ + + #include +-#include // memcpy ++#include /* memcpy */ + + #if defined(_MSC_VER) && (_MSC_VER <= 1700) + /* for vs2012/11.0/1700 and earlier Visual Studio compilers */ +@@ -66,7 +66,6 @@ + { PREFIX(prologTok), PREFIX(contentTok), \ + PREFIX(cdataSectionTok) IGNORE_SECTION_TOK_VTABLE }, \ + { PREFIX(attributeValueTok), PREFIX(entityValueTok) }, \ +- PREFIX(sameName), \ + PREFIX(nameMatchesAscii), \ + PREFIX(nameLength), \ + PREFIX(skipS), \ +@@ -363,7 +362,7 @@ enum { /* UTF8_cvalN is value of masked first byte of N byte sequence */ + }; + + void +-align_limit_to_full_utf8_characters(const char * from, const char ** fromLimRef) ++_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef) + { + const char * fromLim = *fromLimRef; + size_t walked = 0; +@@ -416,7 +415,7 @@ utf8_toUtf8(const ENCODING *UNUSED_P(enc), + /* Avoid copying partial characters (from incomplete input). */ + { + const char * const fromLimBefore = fromLim; +- align_limit_to_full_utf8_characters(*fromP, &fromLim); ++ _INTERNAL_trim_to_complete_utf8_characters(*fromP, &fromLim); + if (fromLim < fromLimBefore) { + input_incomplete = true; + } +@@ -424,12 +423,12 @@ utf8_toUtf8(const ENCODING *UNUSED_P(enc), + + { + const ptrdiff_t bytesToCopy = fromLim - *fromP; +- memcpy((void *)*toP, (const void *)*fromP, (size_t)bytesToCopy); ++ memcpy(*toP, *fromP, bytesToCopy); + *fromP += bytesToCopy; + *toP += bytesToCopy; + } + +- if (output_exhausted) // needs to go first ++ if (output_exhausted) /* needs to go first */ + return XML_CONVERT_OUTPUT_EXHAUSTED; + else if (input_incomplete) + return XML_CONVERT_INPUT_INCOMPLETE; +@@ -1465,9 +1464,8 @@ unknown_toUtf8(const ENCODING *enc, + return XML_CONVERT_OUTPUT_EXHAUSTED; + (*fromP)++; + } +- do { +- *(*toP)++ = *utf8++; +- } while (--n != 0); ++ memcpy(*toP, utf8, n); ++ *toP += n; + } + } + +diff --git a/Modules/expat/xmltok.h b/Modules/expat/xmltok.h +index 6d31879b33..50926f38ab 100644 +--- a/Modules/expat/xmltok.h ++++ b/Modules/expat/xmltok.h +@@ -167,9 +167,6 @@ enum XML_Convert_Result { + struct encoding { + SCANNER scanners[XML_N_STATES]; + SCANNER literalScanners[XML_N_LITERAL_TYPES]; +- int (PTRCALL *sameName)(const ENCODING *, +- const char *, +- const char *); + int (PTRCALL *nameMatchesAscii)(const ENCODING *, + const char *, + const char *, +@@ -260,8 +257,6 @@ struct encoding { + #define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \ + XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr) + +-#define XmlSameName(enc, ptr1, ptr2) (((enc)->sameName)(enc, ptr1, ptr2)) +- + #define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \ + (((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2)) + +diff --git a/Modules/expat/xmltok_impl.c b/Modules/expat/xmltok_impl.c +index 93328b841a..4d9ae7dc38 100644 +--- a/Modules/expat/xmltok_impl.c ++++ b/Modules/expat/xmltok_impl.c +@@ -74,6 +74,7 @@ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ ++ /* fall through */ \ + case BT_NMSTRT: \ + case BT_HEX: \ + case BT_DIGIT: \ +@@ -102,6 +103,7 @@ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ ++ /* fall through */ \ + case BT_NMSTRT: \ + case BT_HEX: \ + ptr += MINBPC(enc); \ +@@ -602,7 +604,7 @@ PREFIX(scanAtts)(const ENCODING *enc, const char *ptr, const char *end, + return XML_TOK_INVALID; + } + } +- /* fall through */ ++ /* fall through */ + case BT_EQUALS: + { + int open; +@@ -1442,6 +1444,7 @@ PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end, + case BT_NMSTRT: + if (!(BYTE_TO_ASCII(enc, ptr) & ~0x7f)) + break; ++ /* fall through */ + default: + switch (BYTE_TO_ASCII(enc, ptr)) { + case 0x24: /* $ */ +@@ -1653,87 +1656,14 @@ PREFIX(predefinedEntityName)(const ENCODING *UNUSED_P(enc), const char *ptr, + return 0; + } + +-/* This function does not appear to be called from anywhere within the +- * library code. It is used via the macro XmlSameName(), which is +- * defined but never used. Since it appears in the encoding function +- * table, removing it is not a thing to be undertaken lightly. For +- * the moment, we simply exclude it from coverage tests. +- * +- * LCOV_EXCL_START +- */ +-static int PTRCALL +-PREFIX(sameName)(const ENCODING *enc, const char *ptr1, const char *ptr2) +-{ +- for (;;) { +- switch (BYTE_TYPE(enc, ptr1)) { +-#define LEAD_CASE(n) \ +- case BT_LEAD ## n: \ +- if (*ptr1++ != *ptr2++) \ +- return 0; +- LEAD_CASE(4) LEAD_CASE(3) LEAD_CASE(2) +-#undef LEAD_CASE +- /* fall through */ +- if (*ptr1++ != *ptr2++) +- return 0; +- break; +- case BT_NONASCII: +- case BT_NMSTRT: +-#ifdef XML_NS +- case BT_COLON: +-#endif +- case BT_HEX: +- case BT_DIGIT: +- case BT_NAME: +- case BT_MINUS: +- if (*ptr2++ != *ptr1++) +- return 0; +- if (MINBPC(enc) > 1) { +- if (*ptr2++ != *ptr1++) +- return 0; +- if (MINBPC(enc) > 2) { +- if (*ptr2++ != *ptr1++) +- return 0; +- if (MINBPC(enc) > 3) { +- if (*ptr2++ != *ptr1++) +- return 0; +- } +- } +- } +- break; +- default: +- if (MINBPC(enc) == 1 && *ptr1 == *ptr2) +- return 1; +- switch (BYTE_TYPE(enc, ptr2)) { +- case BT_LEAD2: +- case BT_LEAD3: +- case BT_LEAD4: +- case BT_NONASCII: +- case BT_NMSTRT: +-#ifdef XML_NS +- case BT_COLON: +-#endif +- case BT_HEX: +- case BT_DIGIT: +- case BT_NAME: +- case BT_MINUS: +- return 0; +- default: +- return 1; +- } +- } +- } +- /* not reached */ +-} +-/* LCOV_EXCL_STOP */ +- + static int PTRCALL + PREFIX(nameMatchesAscii)(const ENCODING *UNUSED_P(enc), const char *ptr1, + const char *end1, const char *ptr2) + { + for (; *ptr2; ptr1 += MINBPC(enc), ptr2++) { + if (end1 - ptr1 < MINBPC(enc)) { +- /* This line cannot be executed. THe incoming data has already +- * been tokenized once, so imcomplete characters like this have ++ /* This line cannot be executed. The incoming data has already ++ * been tokenized once, so incomplete characters like this have + * already been eliminated from the input. Retaining the + * paranoia check is still valuable, however. + */ +diff --git a/Modules/gcmodule.c b/Modules/gcmodule.c +index 916e4817d9..700c1a32b0 100644 +--- a/Modules/gcmodule.c ++++ b/Modules/gcmodule.c +@@ -771,10 +771,8 @@ debug_cycle(char *msg, PyObject *op) + * garbage list (a Python list), else only the objects in finalizers with + * __del__ methods are appended to garbage. All objects in finalizers are + * merged into the old list regardless. +- * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list). +- * The finalizers list is made empty on a successful return. + */ +-static int ++static void + handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old) + { + PyGC_Head *gc = finalizers->gc.gc_next; +@@ -789,12 +787,11 @@ handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old) + + if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) { + if (PyList_Append(garbage, op) < 0) +- return -1; ++ break; + } + } + + gc_list_merge(finalizers, old); +- return 0; + } + + /* Break reference cycles by clearing the containers involved. This is +@@ -1012,7 +1009,7 @@ collect(int generation) + * reachable list of garbage. The programmer has to deal with + * this if they insist on creating this type of structure. + */ +- (void)handle_finalizers(&finalizers, old); ++ handle_finalizers(&finalizers, old); + + /* Clear free list only during the collection of the highest + * generation */ +@@ -1436,8 +1433,11 @@ PyGC_Collect(void) + if (collecting) + n = 0; /* already collecting, don't do anything */ + else { ++ PyObject *exc, *value, *tb; + collecting = 1; ++ PyErr_Fetch(&exc, &value, &tb); + n = collect(NUM_GENERATIONS - 1); ++ PyErr_Restore(exc, value, tb); + collecting = 0; + } + +@@ -1539,6 +1539,7 @@ _PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems) + { + const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems); + PyGC_Head *g = AS_GC(op); ++ assert(!IS_TRACKED(op)); + if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) + return (PyVarObject *)PyErr_NoMemory(); + g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize); +diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c +index 01ed36b213..67354a7594 100644 +--- a/Modules/mathmodule.c ++++ b/Modules/mathmodule.c +@@ -1188,7 +1188,7 @@ math_ldexp(PyObject *self, PyObject *args) + if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp)) + return NULL; + +- if (PyLong_Check(oexp) || PyInt_Check(oexp)) { ++ if (_PyAnyInt_Check(oexp)) { + /* on overflow, replace exponent with either LONG_MAX + or LONG_MIN, depending on the sign. */ + exp = PyLong_AsLongAndOverflow(oexp, &overflow); +diff --git a/Modules/md5module.c b/Modules/md5module.c +index 103da1497d..dd90a22c00 100644 +--- a/Modules/md5module.c ++++ b/Modules/md5module.c +@@ -236,7 +236,7 @@ copy() -- return a copy of the current md5 object"); + static PyTypeObject MD5type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_md5.md5", /*tp_name*/ +- sizeof(md5object), /*tp_size*/ ++ sizeof(md5object), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)md5_dealloc, /*tp_dealloc*/ +diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c +index 2ae52c7b28..02b31ca438 100644 +--- a/Modules/mmapmodule.c ++++ b/Modules/mmapmodule.c +@@ -818,24 +818,6 @@ mmap_subscript(mmap_object *self, PyObject *item) + } + } + +-static PyObject * +-mmap_concat(mmap_object *self, PyObject *bb) +-{ +- CHECK_VALID(NULL); +- PyErr_SetString(PyExc_SystemError, +- "mmaps don't support concatenation"); +- return NULL; +-} +- +-static PyObject * +-mmap_repeat(mmap_object *self, Py_ssize_t n) +-{ +- CHECK_VALID(NULL); +- PyErr_SetString(PyExc_SystemError, +- "mmaps don't support repeat operation"); +- return NULL; +-} +- + static int + mmap_ass_slice(mmap_object *self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) + { +@@ -993,9 +975,9 @@ mmap_ass_subscript(mmap_object *self, PyObject *item, PyObject *value) + + static PySequenceMethods mmap_as_sequence = { + (lenfunc)mmap_length, /*sq_length*/ +- (binaryfunc)mmap_concat, /*sq_concat*/ +- (ssizeargfunc)mmap_repeat, /*sq_repeat*/ +- (ssizeargfunc)mmap_item, /*sq_item*/ ++ 0, /*sq_concat*/ ++ 0, /*sq_repeat*/ ++ (ssizeargfunc)mmap_item, /*sq_item*/ + (ssizessizeargfunc)mmap_slice, /*sq_slice*/ + (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/ + (ssizessizeobjargproc)mmap_ass_slice, /*sq_ass_slice*/ +@@ -1044,7 +1026,7 @@ To map anonymous memory, pass -1 as the fileno (both versions)."); + static PyTypeObject mmap_object_type = { + PyVarObject_HEAD_INIT(NULL, 0) + "mmap.mmap", /* tp_name */ +- sizeof(mmap_object), /* tp_size */ ++ sizeof(mmap_object), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor) mmap_object_dealloc, /* tp_dealloc */ +diff --git a/Modules/ossaudiodev.c b/Modules/ossaudiodev.c +index 284cc61076..f833bb257f 100644 +--- a/Modules/ossaudiodev.c ++++ b/Modules/ossaudiodev.c +@@ -842,7 +842,7 @@ oss_mixer_getattr(oss_mixer_t *self, char *name) + static PyTypeObject OSSAudioType = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "ossaudiodev.oss_audio_device", /*tp_name*/ +- sizeof(oss_audio_t), /*tp_size*/ ++ sizeof(oss_audio_t), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)oss_dealloc, /*tp_dealloc*/ +@@ -856,7 +856,7 @@ static PyTypeObject OSSAudioType = { + static PyTypeObject OSSMixerType = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "ossaudiodev.oss_mixer_device", /*tp_name*/ +- sizeof(oss_mixer_t), /*tp_size*/ ++ sizeof(oss_mixer_t), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)oss_mixer_dealloc, /*tp_dealloc*/ +diff --git a/Modules/parsermodule.c b/Modules/parsermodule.c +index 79555428d1..fcc618d5d9 100644 +--- a/Modules/parsermodule.c ++++ b/Modules/parsermodule.c +@@ -121,10 +121,10 @@ node2tuple(node *n, /* node to convert */ + if (result != NULL) { + (void) addelem(result, 0, PyInt_FromLong(TYPE(n))); + (void) addelem(result, 1, PyString_FromString(STR(n))); +- if (lineno == 1) ++ if (lineno) + (void) addelem(result, 2, PyInt_FromLong(n->n_lineno)); +- if (col_offset == 1) +- (void) addelem(result, 3, PyInt_FromLong(n->n_col_offset)); ++ if (col_offset) ++ (void) addelem(result, 2 + lineno, PyInt_FromLong(n->n_col_offset)); + } + return (result); + } +diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c +index 2baf9202c3..7a1a6945c1 100644 +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -6121,7 +6121,7 @@ posix_setgroups(PyObject *self, PyObject *groups) + elem = PySequence_GetItem(groups, i); + if (!elem) + return NULL; +- if (!PyInt_Check(elem) && !PyLong_Check(elem)) { ++ if (!_PyAnyInt_Check(elem)) { + PyErr_SetString(PyExc_TypeError, + "groups must be integers"); + Py_DECREF(elem); +diff --git a/Modules/pyexpat.c b/Modules/pyexpat.c +index 2b4d31293c..1f8c0d70a5 100644 +--- a/Modules/pyexpat.c ++++ b/Modules/pyexpat.c +@@ -2042,6 +2042,11 @@ MODULE_INITFUNC(void) + capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler; + capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler; + capi.SetUserData = XML_SetUserData; ++#if XML_COMBINED_VERSION >= 20100 ++ capi.SetHashSalt = XML_SetHashSalt; ++#else ++ capi.SetHashSalt = NULL; ++#endif + + /* export using capsule */ + capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL); +diff --git a/Modules/sha256module.c b/Modules/sha256module.c +index 8f18faa17a..76e52209f6 100644 +--- a/Modules/sha256module.c ++++ b/Modules/sha256module.c +@@ -537,7 +537,7 @@ static PyMemberDef SHA_members[] = { + static PyTypeObject SHA224type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_sha256.sha224", /*tp_name*/ +- sizeof(SHAobject), /*tp_size*/ ++ sizeof(SHAobject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + SHA_dealloc, /*tp_dealloc*/ +@@ -571,7 +571,7 @@ static PyTypeObject SHA224type = { + static PyTypeObject SHA256type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_sha256.sha256", /*tp_name*/ +- sizeof(SHAobject), /*tp_size*/ ++ sizeof(SHAobject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + SHA_dealloc, /*tp_dealloc*/ +diff --git a/Modules/sha512module.c b/Modules/sha512module.c +index abc9021805..e3733e0443 100644 +--- a/Modules/sha512module.c ++++ b/Modules/sha512module.c +@@ -603,7 +603,7 @@ static PyMemberDef SHA_members[] = { + static PyTypeObject SHA384type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_sha512.sha384", /*tp_name*/ +- sizeof(SHAobject), /*tp_size*/ ++ sizeof(SHAobject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + SHA512_dealloc, /*tp_dealloc*/ +@@ -637,7 +637,7 @@ static PyTypeObject SHA384type = { + static PyTypeObject SHA512type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_sha512.sha512", /*tp_name*/ +- sizeof(SHAobject), /*tp_size*/ ++ sizeof(SHAobject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + SHA512_dealloc, /*tp_dealloc*/ +diff --git a/Modules/signalmodule.c b/Modules/signalmodule.c +index ef70d10bb1..8628f7a800 100644 +--- a/Modules/signalmodule.c ++++ b/Modules/signalmodule.c +@@ -95,13 +95,6 @@ static PyObject *DefaultHandler; + static PyObject *IgnoreHandler; + static PyObject *IntHandler; + +-/* On Solaris 8, gcc will produce a warning that the function +- declaration is not a prototype. This is caused by the definition of +- SIG_DFL as (void (*)())0; the correct declaration would have been +- (void (*)(int))0. */ +- +-static PyOS_sighandler_t old_siginthandler = SIG_DFL; +- + #ifdef HAVE_GETITIMER + static PyObject *ItimerError; + +@@ -629,7 +622,7 @@ initsignal(void) + /* Install default int handler */ + Py_INCREF(IntHandler); + Py_SETREF(Handlers[SIGINT].func, IntHandler); +- old_siginthandler = PyOS_setsig(SIGINT, signal_handler); ++ PyOS_setsig(SIGINT, signal_handler); + } + + #ifdef SIGHUP +@@ -872,14 +865,11 @@ finisignal(void) + int i; + PyObject *func; + +- PyOS_setsig(SIGINT, old_siginthandler); +- old_siginthandler = SIG_DFL; +- + for (i = 1; i < NSIG; i++) { + func = Handlers[i].func; + Handlers[i].tripped = 0; + Handlers[i].func = NULL; +- if (i != SIGINT && func != NULL && func != Py_None && ++ if (func != NULL && func != Py_None && + func != DefaultHandler && func != IgnoreHandler) + PyOS_setsig(i, SIG_DFL); + Py_XDECREF(func); +diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c +index 8d3670529e..634c1b9077 100644 +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -4194,7 +4194,7 @@ socket_getaddrinfo(PyObject *self, PyObject *args) + "getaddrinfo() argument 1 must be string or None"); + return NULL; + } +- if (PyInt_Check(pobj) || PyLong_Check(pobj)) { ++ if (_PyAnyInt_Check(pobj)) { + long value = PyLong_AsLong(pobj); + if (value == -1 && PyErr_Occurred()) + return NULL; +diff --git a/Modules/svmodule.c b/Modules/svmodule.c +index 42c49c853a..14f236cb16 100644 +--- a/Modules/svmodule.c ++++ b/Modules/svmodule.c +@@ -686,7 +686,7 @@ sv_LoadMap(svobject *self, PyObject *args) + if (!cell) + goto finally; + +- if (!PyInt_Check(cell) && !PyLong_Check(cell)) { ++ if (!_PyAnyInt_Check(cell)) { + PyErr_BadArgument(); + goto finally; + } +@@ -757,7 +757,7 @@ doParams(svobject *self, PyObject *args, + if (!v) + goto finally; + +- if (!PyInt_Check(v) && !PyLong_Check(v)) { ++ if (!_PyAnyInt_Check(v)) { + PyErr_BadArgument(); + goto finally; + } +diff --git a/Modules/termios.c b/Modules/termios.c +index 9d4d780dca..e26e714e0e 100644 +--- a/Modules/termios.c ++++ b/Modules/termios.c +@@ -185,7 +185,7 @@ termios_tcsetattr(PyObject *self, PyObject *args) + + if (PyString_Check(v) && PyString_Size(v) == 1) + mode.c_cc[i] = (cc_t) * PyString_AsString(v); +- else if (PyInt_Check(v) || PyLong_Check(v)) { ++ else if (_PyAnyInt_Check(v)) { + mode.c_cc[i] = (cc_t) PyInt_AsLong(v); + if (mode.c_cc[i] == (cc_t) -1 && PyErr_Occurred()) + return NULL; +diff --git a/Modules/unicodedata.c b/Modules/unicodedata.c +index 6b01fc7616..df6ffe343c 100644 +--- a/Modules/unicodedata.c ++++ b/Modules/unicodedata.c +@@ -664,14 +664,18 @@ nfc_nfkc(PyObject *self, PyObject *input, int k) + pairs, since we always have decomposed data. */ + if (LBase <= *i && *i < (LBase+LCount) && + i + 1 < end && +- VBase <= i[1] && i[1] <= (VBase+VCount)) { ++ VBase <= i[1] && i[1] < (VBase+VCount)) { ++ /* check L character is a modern leading consonant (0x1100 ~ 0x1112) ++ and V character is a modern vowel (0x1161 ~ 0x1175). */ + int LIndex, VIndex; + LIndex = i[0] - LBase; + VIndex = i[1] - VBase; + code = SBase + (LIndex*VCount+VIndex)*TCount; + i+=2; + if (i < end && +- TBase <= *i && *i <= (TBase+TCount)) { ++ TBase < *i && *i < (TBase+TCount)) { ++ /* check T character is a modern trailing consonant ++ (0x11A8 ~ 0x11C2). */ + code += *i-TBase; + i++; + } +diff --git a/Objects/abstract.c b/Objects/abstract.c +index aa92ea9156..75c1a10473 100644 +--- a/Objects/abstract.c ++++ b/Objects/abstract.c +@@ -1492,14 +1492,13 @@ PyNumber_Index(PyObject *item) + PyObject *result = NULL; + if (item == NULL) + return null_error(); +- if (PyInt_Check(item) || PyLong_Check(item)) { ++ if (_PyAnyInt_Check(item)) { + Py_INCREF(item); + return item; + } + if (PyIndex_Check(item)) { + result = item->ob_type->tp_as_number->nb_index(item); +- if (result && +- !PyInt_Check(result) && !PyLong_Check(result)) { ++ if (result && !_PyAnyInt_Check(result)) { + PyErr_Format(PyExc_TypeError, + "__index__ returned non-(int,long) " \ + "(type %.200s)", +@@ -1574,8 +1573,7 @@ _PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format) + return NULL; + } + +- if (integral && (!PyInt_Check(integral) && +- !PyLong_Check(integral))) { ++ if (integral && !_PyAnyInt_Check(integral)) { + /* Don't go through tp_as_number->nb_int to avoid + hitting the classic class fallback to __trunc__. */ + PyObject *int_func = PyObject_GetAttr(integral, int_name); +@@ -1586,8 +1584,7 @@ _PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format) + Py_DECREF(integral); + integral = PyEval_CallObject(int_func, NULL); + Py_DECREF(int_func); +- if (integral && (!PyInt_Check(integral) && +- !PyLong_Check(integral))) { ++ if (integral && !_PyAnyInt_Check(integral)) { + goto non_integral_error; + } + } +@@ -1632,7 +1629,7 @@ PyNumber_Int(PyObject *o) + if (m && m->nb_int) { /* This should include subclasses of int */ + /* Classic classes always take this branch. */ + PyObject *res = m->nb_int(o); +- if (res && (!PyInt_Check(res) && !PyLong_Check(res))) { ++ if (res && !_PyAnyInt_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type %.200s)", + res->ob_type->tp_name); +diff --git a/Objects/bytearrayobject.c b/Objects/bytearrayobject.c +index 04c25061ef..c178d9ef65 100644 +--- a/Objects/bytearrayobject.c ++++ b/Objects/bytearrayobject.c +@@ -35,7 +35,7 @@ _getbytevalue(PyObject* arg, int *value) + *value = Py_CHARMASK(((PyBytesObject*)arg)->ob_sval[0]); + return 1; + } +- else if (PyInt_Check(arg) || PyLong_Check(arg)) { ++ else if (_PyAnyInt_Check(arg)) { + face_value = PyLong_AsLong(arg); + } + else { +diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c +deleted file mode 100644 +index 7ba90aa307..0000000000 ++++ /dev/null +@@ -1,3432 +0,0 @@ +-/* bytes object implementation */ +- +-#define PY_SSIZE_T_CLEAN +- +-#include "Python.h" +-#include "internal/mem.h" +-#include "internal/pystate.h" +- +-#include "bytes_methods.h" +-#include "pystrhex.h" +-#include +- +-/*[clinic input] +-class bytes "PyBytesObject *" "&PyBytes_Type" +-[clinic start generated code]*/ +-/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7a238f965d64892b]*/ +- +-#include "clinic/bytesobject.c.h" +- +-#ifdef COUNT_ALLOCS +-Py_ssize_t null_strings, one_strings; +-#endif +- +-static PyBytesObject *characters[UCHAR_MAX + 1]; +-static PyBytesObject *nullstring; +- +-/* PyBytesObject_SIZE gives the basic size of a string; any memory allocation +- for a string of length n should request PyBytesObject_SIZE + n bytes. +- +- Using PyBytesObject_SIZE instead of sizeof(PyBytesObject) saves +- 3 bytes per string allocation on a typical system. +-*/ +-#define PyBytesObject_SIZE (offsetof(PyBytesObject, ob_sval) + 1) +- +-/* Forward declaration */ +-Py_LOCAL_INLINE(Py_ssize_t) _PyBytesWriter_GetSize(_PyBytesWriter *writer, +- char *str); +- +-/* +- For PyBytes_FromString(), the parameter `str' points to a null-terminated +- string containing exactly `size' bytes. +- +- For PyBytes_FromStringAndSize(), the parameter `str' is +- either NULL or else points to a string containing at least `size' bytes. +- For PyBytes_FromStringAndSize(), the string in the `str' parameter does +- not have to be null-terminated. (Therefore it is safe to construct a +- substring by calling `PyBytes_FromStringAndSize(origstring, substrlen)'.) +- If `str' is NULL then PyBytes_FromStringAndSize() will allocate `size+1' +- bytes (setting the last byte to the null terminating character) and you can +- fill in the data yourself. If `str' is non-NULL then the resulting +- PyBytes object must be treated as immutable and you must not fill in nor +- alter the data yourself, since the strings may be shared. +- +- The PyObject member `op->ob_size', which denotes the number of "extra +- items" in a variable-size object, will contain the number of bytes +- allocated for string data, not counting the null terminating character. +- It is therefore equal to the `size' parameter (for +- PyBytes_FromStringAndSize()) or the length of the string in the `str' +- parameter (for PyBytes_FromString()). +-*/ +-static PyObject * +-_PyBytes_FromSize(Py_ssize_t size, int use_calloc) +-{ +- PyBytesObject *op; +- assert(size >= 0); +- +- if (size == 0 && (op = nullstring) != NULL) { +-#ifdef COUNT_ALLOCS +- null_strings++; +-#endif +- Py_INCREF(op); +- return (PyObject *)op; +- } +- +- if ((size_t)size > (size_t)PY_SSIZE_T_MAX - PyBytesObject_SIZE) { +- PyErr_SetString(PyExc_OverflowError, +- "byte string is too large"); +- return NULL; +- } +- +- /* Inline PyObject_NewVar */ +- if (use_calloc) +- op = (PyBytesObject *)PyObject_Calloc(1, PyBytesObject_SIZE + size); +- else +- op = (PyBytesObject *)PyObject_Malloc(PyBytesObject_SIZE + size); +- if (op == NULL) +- return PyErr_NoMemory(); +- (void)PyObject_INIT_VAR(op, &PyBytes_Type, size); +- op->ob_shash = -1; +- if (!use_calloc) +- op->ob_sval[size] = '\0'; +- /* empty byte string singleton */ +- if (size == 0) { +- nullstring = op; +- Py_INCREF(op); +- } +- return (PyObject *) op; +-} +- +-PyObject * +-PyBytes_FromStringAndSize(const char *str, Py_ssize_t size) +-{ +- PyBytesObject *op; +- if (size < 0) { +- PyErr_SetString(PyExc_SystemError, +- "Negative size passed to PyBytes_FromStringAndSize"); +- return NULL; +- } +- if (size == 1 && str != NULL && +- (op = characters[*str & UCHAR_MAX]) != NULL) +- { +-#ifdef COUNT_ALLOCS +- one_strings++; +-#endif +- Py_INCREF(op); +- return (PyObject *)op; +- } +- +- op = (PyBytesObject *)_PyBytes_FromSize(size, 0); +- if (op == NULL) +- return NULL; +- if (str == NULL) +- return (PyObject *) op; +- +- memcpy(op->ob_sval, str, size); +- /* share short strings */ +- if (size == 1) { +- characters[*str & UCHAR_MAX] = op; +- Py_INCREF(op); +- } +- return (PyObject *) op; +-} +- +-PyObject * +-PyBytes_FromString(const char *str) +-{ +- size_t size; +- PyBytesObject *op; +- +- assert(str != NULL); +- size = strlen(str); +- if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) { +- PyErr_SetString(PyExc_OverflowError, +- "byte string is too long"); +- return NULL; +- } +- if (size == 0 && (op = nullstring) != NULL) { +-#ifdef COUNT_ALLOCS +- null_strings++; +-#endif +- Py_INCREF(op); +- return (PyObject *)op; +- } +- if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) { +-#ifdef COUNT_ALLOCS +- one_strings++; +-#endif +- Py_INCREF(op); +- return (PyObject *)op; +- } +- +- /* Inline PyObject_NewVar */ +- op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); +- if (op == NULL) +- return PyErr_NoMemory(); +- (void)PyObject_INIT_VAR(op, &PyBytes_Type, size); +- op->ob_shash = -1; +- memcpy(op->ob_sval, str, size+1); +- /* share short strings */ +- if (size == 0) { +- nullstring = op; +- Py_INCREF(op); +- } else if (size == 1) { +- characters[*str & UCHAR_MAX] = op; +- Py_INCREF(op); +- } +- return (PyObject *) op; +-} +- +-PyObject * +-PyBytes_FromFormatV(const char *format, va_list vargs) +-{ +- char *s; +- const char *f; +- const char *p; +- Py_ssize_t prec; +- int longflag; +- int size_tflag; +- /* Longest 64-bit formatted numbers: +- - "18446744073709551615\0" (21 bytes) +- - "-9223372036854775808\0" (21 bytes) +- Decimal takes the most space (it isn't enough for octal.) +- +- Longest 64-bit pointer representation: +- "0xffffffffffffffff\0" (19 bytes). */ +- char buffer[21]; +- _PyBytesWriter writer; +- +- _PyBytesWriter_Init(&writer); +- +- s = _PyBytesWriter_Alloc(&writer, strlen(format)); +- if (s == NULL) +- return NULL; +- writer.overallocate = 1; +- +-#define WRITE_BYTES(str) \ +- do { \ +- s = _PyBytesWriter_WriteBytes(&writer, s, (str), strlen(str)); \ +- if (s == NULL) \ +- goto error; \ +- } while (0) +- +- for (f = format; *f; f++) { +- if (*f != '%') { +- *s++ = *f; +- continue; +- } +- +- p = f++; +- +- /* ignore the width (ex: 10 in "%10s") */ +- while (Py_ISDIGIT(*f)) +- f++; +- +- /* parse the precision (ex: 10 in "%.10s") */ +- prec = 0; +- if (*f == '.') { +- f++; +- for (; Py_ISDIGIT(*f); f++) { +- prec = (prec * 10) + (*f - '0'); +- } +- } +- +- while (*f && *f != '%' && !Py_ISALPHA(*f)) +- f++; +- +- /* handle the long flag ('l'), but only for %ld and %lu. +- others can be added when necessary. */ +- longflag = 0; +- if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { +- longflag = 1; +- ++f; +- } +- +- /* handle the size_t flag ('z'). */ +- size_tflag = 0; +- if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { +- size_tflag = 1; +- ++f; +- } +- +- /* subtract bytes preallocated for the format string +- (ex: 2 for "%s") */ +- writer.min_size -= (f - p + 1); +- +- switch (*f) { +- case 'c': +- { +- int c = va_arg(vargs, int); +- if (c < 0 || c > 255) { +- PyErr_SetString(PyExc_OverflowError, +- "PyBytes_FromFormatV(): %c format " +- "expects an integer in range [0; 255]"); +- goto error; +- } +- writer.min_size++; +- *s++ = (unsigned char)c; +- break; +- } +- +- case 'd': +- if (longflag) +- sprintf(buffer, "%ld", va_arg(vargs, long)); +- else if (size_tflag) +- sprintf(buffer, "%" PY_FORMAT_SIZE_T "d", +- va_arg(vargs, Py_ssize_t)); +- else +- sprintf(buffer, "%d", va_arg(vargs, int)); +- assert(strlen(buffer) < sizeof(buffer)); +- WRITE_BYTES(buffer); +- break; +- +- case 'u': +- if (longflag) +- sprintf(buffer, "%lu", +- va_arg(vargs, unsigned long)); +- else if (size_tflag) +- sprintf(buffer, "%" PY_FORMAT_SIZE_T "u", +- va_arg(vargs, size_t)); +- else +- sprintf(buffer, "%u", +- va_arg(vargs, unsigned int)); +- assert(strlen(buffer) < sizeof(buffer)); +- WRITE_BYTES(buffer); +- break; +- +- case 'i': +- sprintf(buffer, "%i", va_arg(vargs, int)); +- assert(strlen(buffer) < sizeof(buffer)); +- WRITE_BYTES(buffer); +- break; +- +- case 'x': +- sprintf(buffer, "%x", va_arg(vargs, int)); +- assert(strlen(buffer) < sizeof(buffer)); +- WRITE_BYTES(buffer); +- break; +- +- case 's': +- { +- Py_ssize_t i; +- +- p = va_arg(vargs, const char*); +- i = strlen(p); +- if (prec > 0 && i > prec) +- i = prec; +- s = _PyBytesWriter_WriteBytes(&writer, s, p, i); +- if (s == NULL) +- goto error; +- break; +- } +- +- case 'p': +- sprintf(buffer, "%p", va_arg(vargs, void*)); +- assert(strlen(buffer) < sizeof(buffer)); +- /* %p is ill-defined: ensure leading 0x. */ +- if (buffer[1] == 'X') +- buffer[1] = 'x'; +- else if (buffer[1] != 'x') { +- memmove(buffer+2, buffer, strlen(buffer)+1); +- buffer[0] = '0'; +- buffer[1] = 'x'; +- } +- WRITE_BYTES(buffer); +- break; +- +- case '%': +- writer.min_size++; +- *s++ = '%'; +- break; +- +- default: +- if (*f == 0) { +- /* fix min_size if we reached the end of the format string */ +- writer.min_size++; +- } +- +- /* invalid format string: copy unformatted string and exit */ +- WRITE_BYTES(p); +- return _PyBytesWriter_Finish(&writer, s); +- } +- } +- +-#undef WRITE_BYTES +- +- return _PyBytesWriter_Finish(&writer, s); +- +- error: +- _PyBytesWriter_Dealloc(&writer); +- return NULL; +-} +- +-PyObject * +-PyBytes_FromFormat(const char *format, ...) +-{ +- PyObject* ret; +- va_list vargs; +- +-#ifdef HAVE_STDARG_PROTOTYPES +- va_start(vargs, format); +-#else +- va_start(vargs); +-#endif +- ret = PyBytes_FromFormatV(format, vargs); +- va_end(vargs); +- return ret; +-} +- +-/* Helpers for formatstring */ +- +-Py_LOCAL_INLINE(PyObject *) +-getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx) +-{ +- Py_ssize_t argidx = *p_argidx; +- if (argidx < arglen) { +- (*p_argidx)++; +- if (arglen < 0) +- return args; +- else +- return PyTuple_GetItem(args, argidx); +- } +- PyErr_SetString(PyExc_TypeError, +- "not enough arguments for format string"); +- return NULL; +-} +- +-/* Format codes +- * F_LJUST '-' +- * F_SIGN '+' +- * F_BLANK ' ' +- * F_ALT '#' +- * F_ZERO '0' +- */ +-#define F_LJUST (1<<0) +-#define F_SIGN (1<<1) +-#define F_BLANK (1<<2) +-#define F_ALT (1<<3) +-#define F_ZERO (1<<4) +- +-/* Returns a new reference to a PyBytes object, or NULL on failure. */ +- +-static char* +-formatfloat(PyObject *v, int flags, int prec, int type, +- PyObject **p_result, _PyBytesWriter *writer, char *str) +-{ +- char *p; +- PyObject *result; +- double x; +- size_t len; +- +- x = PyFloat_AsDouble(v); +- if (x == -1.0 && PyErr_Occurred()) { +- PyErr_Format(PyExc_TypeError, "float argument required, " +- "not %.200s", Py_TYPE(v)->tp_name); +- return NULL; +- } +- +- if (prec < 0) +- prec = 6; +- +- p = PyOS_double_to_string(x, type, prec, +- (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL); +- +- if (p == NULL) +- return NULL; +- +- len = strlen(p); +- if (writer != NULL) { +- str = _PyBytesWriter_Prepare(writer, str, len); +- if (str == NULL) +- return NULL; +- memcpy(str, p, len); +- PyMem_Free(p); +- str += len; +- return str; +- } +- +- result = PyBytes_FromStringAndSize(p, len); +- PyMem_Free(p); +- *p_result = result; +- return str; +-} +- +-static PyObject * +-formatlong(PyObject *v, int flags, int prec, int type) +-{ +- PyObject *result, *iobj; +- if (type == 'i') +- type = 'd'; +- if (PyLong_Check(v)) +- return _PyUnicode_FormatLong(v, flags & F_ALT, prec, type); +- if (PyNumber_Check(v)) { +- /* make sure number is a type of integer for o, x, and X */ +- if (type == 'o' || type == 'x' || type == 'X') +- iobj = PyNumber_Index(v); +- else +- iobj = PyNumber_Long(v); +- if (iobj == NULL) { +- if (!PyErr_ExceptionMatches(PyExc_TypeError)) +- return NULL; +- } +- else if (!PyLong_Check(iobj)) +- Py_CLEAR(iobj); +- if (iobj != NULL) { +- result = _PyUnicode_FormatLong(iobj, flags & F_ALT, prec, type); +- Py_DECREF(iobj); +- return result; +- } +- } +- PyErr_Format(PyExc_TypeError, +- "%%%c format: %s is required, not %.200s", type, +- (type == 'o' || type == 'x' || type == 'X') ? "an integer" +- : "a number", +- Py_TYPE(v)->tp_name); +- return NULL; +-} +- +-static int +-byte_converter(PyObject *arg, char *p) +-{ +- if (PyBytes_Check(arg) && PyBytes_GET_SIZE(arg) == 1) { +- *p = PyBytes_AS_STRING(arg)[0]; +- return 1; +- } +- else if (PyByteArray_Check(arg) && PyByteArray_GET_SIZE(arg) == 1) { +- *p = PyByteArray_AS_STRING(arg)[0]; +- return 1; +- } +- else { +- PyObject *iobj; +- long ival; +- int overflow; +- /* make sure number is a type of integer */ +- if (PyLong_Check(arg)) { +- ival = PyLong_AsLongAndOverflow(arg, &overflow); +- } +- else { +- iobj = PyNumber_Index(arg); +- if (iobj == NULL) { +- if (!PyErr_ExceptionMatches(PyExc_TypeError)) +- return 0; +- goto onError; +- } +- ival = PyLong_AsLongAndOverflow(iobj, &overflow); +- Py_DECREF(iobj); +- } +- if (!overflow && ival == -1 && PyErr_Occurred()) +- goto onError; +- if (overflow || !(0 <= ival && ival <= 255)) { +- PyErr_SetString(PyExc_OverflowError, +- "%c arg not in range(256)"); +- return 0; +- } +- *p = (char)ival; +- return 1; +- } +- onError: +- PyErr_SetString(PyExc_TypeError, +- "%c requires an integer in range(256) or a single byte"); +- return 0; +-} +- +-static PyObject *_PyBytes_FromBuffer(PyObject *x); +- +-static PyObject * +-format_obj(PyObject *v, const char **pbuf, Py_ssize_t *plen) +-{ +- PyObject *func, *result; +- _Py_IDENTIFIER(__bytes__); +- /* is it a bytes object? */ +- if (PyBytes_Check(v)) { +- *pbuf = PyBytes_AS_STRING(v); +- *plen = PyBytes_GET_SIZE(v); +- Py_INCREF(v); +- return v; +- } +- if (PyByteArray_Check(v)) { +- *pbuf = PyByteArray_AS_STRING(v); +- *plen = PyByteArray_GET_SIZE(v); +- Py_INCREF(v); +- return v; +- } +- /* does it support __bytes__? */ +- func = _PyObject_LookupSpecial(v, &PyId___bytes__); +- if (func != NULL) { +- result = _PyObject_CallNoArg(func); +- Py_DECREF(func); +- if (result == NULL) +- return NULL; +- if (!PyBytes_Check(result)) { +- PyErr_Format(PyExc_TypeError, +- "__bytes__ returned non-bytes (type %.200s)", +- Py_TYPE(result)->tp_name); +- Py_DECREF(result); +- return NULL; +- } +- *pbuf = PyBytes_AS_STRING(result); +- *plen = PyBytes_GET_SIZE(result); +- return result; +- } +- /* does it support buffer protocol? */ +- if (PyObject_CheckBuffer(v)) { +- /* maybe we can avoid making a copy of the buffer object here? */ +- result = _PyBytes_FromBuffer(v); +- if (result == NULL) +- return NULL; +- *pbuf = PyBytes_AS_STRING(result); +- *plen = PyBytes_GET_SIZE(result); +- return result; +- } +- PyErr_Format(PyExc_TypeError, +- "%%b requires a bytes-like object, " +- "or an object that implements __bytes__, not '%.100s'", +- Py_TYPE(v)->tp_name); +- return NULL; +-} +- +-/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */ +- +-PyObject * +-_PyBytes_FormatEx(const char *format, Py_ssize_t format_len, +- PyObject *args, int use_bytearray) +-{ +- const char *fmt; +- char *res; +- Py_ssize_t arglen, argidx; +- Py_ssize_t fmtcnt; +- int args_owned = 0; +- PyObject *dict = NULL; +- _PyBytesWriter writer; +- +- if (args == NULL) { +- PyErr_BadInternalCall(); +- return NULL; +- } +- fmt = format; +- fmtcnt = format_len; +- +- _PyBytesWriter_Init(&writer); +- writer.use_bytearray = use_bytearray; +- +- res = _PyBytesWriter_Alloc(&writer, fmtcnt); +- if (res == NULL) +- return NULL; +- if (!use_bytearray) +- writer.overallocate = 1; +- +- if (PyTuple_Check(args)) { +- arglen = PyTuple_GET_SIZE(args); +- argidx = 0; +- } +- else { +- arglen = -1; +- argidx = -2; +- } +- if (Py_TYPE(args)->tp_as_mapping && Py_TYPE(args)->tp_as_mapping->mp_subscript && +- !PyTuple_Check(args) && !PyBytes_Check(args) && !PyUnicode_Check(args) && +- !PyByteArray_Check(args)) { +- dict = args; +- } +- +- while (--fmtcnt >= 0) { +- if (*fmt != '%') { +- Py_ssize_t len; +- char *pos; +- +- pos = (char *)memchr(fmt + 1, '%', fmtcnt); +- if (pos != NULL) +- len = pos - fmt; +- else +- len = fmtcnt + 1; +- assert(len != 0); +- +- memcpy(res, fmt, len); +- res += len; +- fmt += len; +- fmtcnt -= (len - 1); +- } +- else { +- /* Got a format specifier */ +- int flags = 0; +- Py_ssize_t width = -1; +- int prec = -1; +- int c = '\0'; +- int fill; +- PyObject *v = NULL; +- PyObject *temp = NULL; +- const char *pbuf = NULL; +- int sign; +- Py_ssize_t len = 0; +- char onechar; /* For byte_converter() */ +- Py_ssize_t alloc; +-#ifdef Py_DEBUG +- char *before; +-#endif +- +- fmt++; +- if (*fmt == '%') { +- *res++ = '%'; +- fmt++; +- fmtcnt--; +- continue; +- } +- if (*fmt == '(') { +- const char *keystart; +- Py_ssize_t keylen; +- PyObject *key; +- int pcount = 1; +- +- if (dict == NULL) { +- PyErr_SetString(PyExc_TypeError, +- "format requires a mapping"); +- goto error; +- } +- ++fmt; +- --fmtcnt; +- keystart = fmt; +- /* Skip over balanced parentheses */ +- while (pcount > 0 && --fmtcnt >= 0) { +- if (*fmt == ')') +- --pcount; +- else if (*fmt == '(') +- ++pcount; +- fmt++; +- } +- keylen = fmt - keystart - 1; +- if (fmtcnt < 0 || pcount > 0) { +- PyErr_SetString(PyExc_ValueError, +- "incomplete format key"); +- goto error; +- } +- key = PyBytes_FromStringAndSize(keystart, +- keylen); +- if (key == NULL) +- goto error; +- if (args_owned) { +- Py_DECREF(args); +- args_owned = 0; +- } +- args = PyObject_GetItem(dict, key); +- Py_DECREF(key); +- if (args == NULL) { +- goto error; +- } +- args_owned = 1; +- arglen = -1; +- argidx = -2; +- } +- +- /* Parse flags. Example: "%+i" => flags=F_SIGN. */ +- while (--fmtcnt >= 0) { +- switch (c = *fmt++) { +- case '-': flags |= F_LJUST; continue; +- case '+': flags |= F_SIGN; continue; +- case ' ': flags |= F_BLANK; continue; +- case '#': flags |= F_ALT; continue; +- case '0': flags |= F_ZERO; continue; +- } +- break; +- } +- +- /* Parse width. Example: "%10s" => width=10 */ +- if (c == '*') { +- v = getnextarg(args, arglen, &argidx); +- if (v == NULL) +- goto error; +- if (!PyLong_Check(v)) { +- PyErr_SetString(PyExc_TypeError, +- "* wants int"); +- goto error; +- } +- width = PyLong_AsSsize_t(v); +- if (width == -1 && PyErr_Occurred()) +- goto error; +- if (width < 0) { +- flags |= F_LJUST; +- width = -width; +- } +- if (--fmtcnt >= 0) +- c = *fmt++; +- } +- else if (c >= 0 && isdigit(c)) { +- width = c - '0'; +- while (--fmtcnt >= 0) { +- c = Py_CHARMASK(*fmt++); +- if (!isdigit(c)) +- break; +- if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) { +- PyErr_SetString( +- PyExc_ValueError, +- "width too big"); +- goto error; +- } +- width = width*10 + (c - '0'); +- } +- } +- +- /* Parse precision. Example: "%.3f" => prec=3 */ +- if (c == '.') { +- prec = 0; +- if (--fmtcnt >= 0) +- c = *fmt++; +- if (c == '*') { +- v = getnextarg(args, arglen, &argidx); +- if (v == NULL) +- goto error; +- if (!PyLong_Check(v)) { +- PyErr_SetString( +- PyExc_TypeError, +- "* wants int"); +- goto error; +- } +- prec = _PyLong_AsInt(v); +- if (prec == -1 && PyErr_Occurred()) +- goto error; +- if (prec < 0) +- prec = 0; +- if (--fmtcnt >= 0) +- c = *fmt++; +- } +- else if (c >= 0 && isdigit(c)) { +- prec = c - '0'; +- while (--fmtcnt >= 0) { +- c = Py_CHARMASK(*fmt++); +- if (!isdigit(c)) +- break; +- if (prec > (INT_MAX - ((int)c - '0')) / 10) { +- PyErr_SetString( +- PyExc_ValueError, +- "prec too big"); +- goto error; +- } +- prec = prec*10 + (c - '0'); +- } +- } +- } /* prec */ +- if (fmtcnt >= 0) { +- if (c == 'h' || c == 'l' || c == 'L') { +- if (--fmtcnt >= 0) +- c = *fmt++; +- } +- } +- if (fmtcnt < 0) { +- PyErr_SetString(PyExc_ValueError, +- "incomplete format"); +- goto error; +- } +- v = getnextarg(args, arglen, &argidx); +- if (v == NULL) +- goto error; +- +- if (fmtcnt < 0) { +- /* last writer: disable writer overallocation */ +- writer.overallocate = 0; +- } +- +- sign = 0; +- fill = ' '; +- switch (c) { +- case 'r': +- // %r is only for 2/3 code; 3 only code should use %a +- case 'a': +- temp = PyObject_ASCII(v); +- if (temp == NULL) +- goto error; +- assert(PyUnicode_IS_ASCII(temp)); +- pbuf = (const char *)PyUnicode_1BYTE_DATA(temp); +- len = PyUnicode_GET_LENGTH(temp); +- if (prec >= 0 && len > prec) +- len = prec; +- break; +- +- case 's': +- // %s is only for 2/3 code; 3 only code should use %b +- case 'b': +- temp = format_obj(v, &pbuf, &len); +- if (temp == NULL) +- goto error; +- if (prec >= 0 && len > prec) +- len = prec; +- break; +- +- case 'i': +- case 'd': +- case 'u': +- case 'o': +- case 'x': +- case 'X': +- if (PyLong_CheckExact(v) +- && width == -1 && prec == -1 +- && !(flags & (F_SIGN | F_BLANK)) +- && c != 'X') +- { +- /* Fast path */ +- int alternate = flags & F_ALT; +- int base; +- +- switch(c) +- { +- default: +- Py_UNREACHABLE(); +- case 'd': +- case 'i': +- case 'u': +- base = 10; +- break; +- case 'o': +- base = 8; +- break; +- case 'x': +- case 'X': +- base = 16; +- break; +- } +- +- /* Fast path */ +- writer.min_size -= 2; /* size preallocated for "%d" */ +- res = _PyLong_FormatBytesWriter(&writer, res, +- v, base, alternate); +- if (res == NULL) +- goto error; +- continue; +- } +- +- temp = formatlong(v, flags, prec, c); +- if (!temp) +- goto error; +- assert(PyUnicode_IS_ASCII(temp)); +- pbuf = (const char *)PyUnicode_1BYTE_DATA(temp); +- len = PyUnicode_GET_LENGTH(temp); +- sign = 1; +- if (flags & F_ZERO) +- fill = '0'; +- break; +- +- case 'e': +- case 'E': +- case 'f': +- case 'F': +- case 'g': +- case 'G': +- if (width == -1 && prec == -1 +- && !(flags & (F_SIGN | F_BLANK))) +- { +- /* Fast path */ +- writer.min_size -= 2; /* size preallocated for "%f" */ +- res = formatfloat(v, flags, prec, c, NULL, &writer, res); +- if (res == NULL) +- goto error; +- continue; +- } +- +- if (!formatfloat(v, flags, prec, c, &temp, NULL, res)) +- goto error; +- pbuf = PyBytes_AS_STRING(temp); +- len = PyBytes_GET_SIZE(temp); +- sign = 1; +- if (flags & F_ZERO) +- fill = '0'; +- break; +- +- case 'c': +- pbuf = &onechar; +- len = byte_converter(v, &onechar); +- if (!len) +- goto error; +- if (width == -1) { +- /* Fast path */ +- *res++ = onechar; +- continue; +- } +- break; +- +- default: +- PyErr_Format(PyExc_ValueError, +- "unsupported format character '%c' (0x%x) " +- "at index %zd", +- c, c, +- (Py_ssize_t)(fmt - 1 - format)); +- goto error; +- } +- +- if (sign) { +- if (*pbuf == '-' || *pbuf == '+') { +- sign = *pbuf++; +- len--; +- } +- else if (flags & F_SIGN) +- sign = '+'; +- else if (flags & F_BLANK) +- sign = ' '; +- else +- sign = 0; +- } +- if (width < len) +- width = len; +- +- alloc = width; +- if (sign != 0 && len == width) +- alloc++; +- /* 2: size preallocated for %s */ +- if (alloc > 2) { +- res = _PyBytesWriter_Prepare(&writer, res, alloc - 2); +- if (res == NULL) +- goto error; +- } +-#ifdef Py_DEBUG +- before = res; +-#endif +- +- /* Write the sign if needed */ +- if (sign) { +- if (fill != ' ') +- *res++ = sign; +- if (width > len) +- width--; +- } +- +- /* Write the numeric prefix for "x", "X" and "o" formats +- if the alternate form is used. +- For example, write "0x" for the "%#x" format. */ +- if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) { +- assert(pbuf[0] == '0'); +- assert(pbuf[1] == c); +- if (fill != ' ') { +- *res++ = *pbuf++; +- *res++ = *pbuf++; +- } +- width -= 2; +- if (width < 0) +- width = 0; +- len -= 2; +- } +- +- /* Pad left with the fill character if needed */ +- if (width > len && !(flags & F_LJUST)) { +- memset(res, fill, width - len); +- res += (width - len); +- width = len; +- } +- +- /* If padding with spaces: write sign if needed and/or numeric +- prefix if the alternate form is used */ +- if (fill == ' ') { +- if (sign) +- *res++ = sign; +- if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) { +- assert(pbuf[0] == '0'); +- assert(pbuf[1] == c); +- *res++ = *pbuf++; +- *res++ = *pbuf++; +- } +- } +- +- /* Copy bytes */ +- memcpy(res, pbuf, len); +- res += len; +- +- /* Pad right with the fill character if needed */ +- if (width > len) { +- memset(res, ' ', width - len); +- res += (width - len); +- } +- +- if (dict && (argidx < arglen)) { +- PyErr_SetString(PyExc_TypeError, +- "not all arguments converted during bytes formatting"); +- Py_XDECREF(temp); +- goto error; +- } +- Py_XDECREF(temp); +- +-#ifdef Py_DEBUG +- /* check that we computed the exact size for this write */ +- assert((res - before) == alloc); +-#endif +- } /* '%' */ +- +- /* If overallocation was disabled, ensure that it was the last +- write. Otherwise, we missed an optimization */ +- assert(writer.overallocate || fmtcnt < 0 || use_bytearray); +- } /* until end */ +- +- if (argidx < arglen && !dict) { +- PyErr_SetString(PyExc_TypeError, +- "not all arguments converted during bytes formatting"); +- goto error; +- } +- +- if (args_owned) { +- Py_DECREF(args); +- } +- return _PyBytesWriter_Finish(&writer, res); +- +- error: +- _PyBytesWriter_Dealloc(&writer); +- if (args_owned) { +- Py_DECREF(args); +- } +- return NULL; +-} +- +-/* =-= */ +- +-static void +-bytes_dealloc(PyObject *op) +-{ +- Py_TYPE(op)->tp_free(op); +-} +- +-/* Unescape a backslash-escaped string. If unicode is non-zero, +- the string is a u-literal. If recode_encoding is non-zero, +- the string is UTF-8 encoded and should be re-encoded in the +- specified encoding. */ +- +-static char * +-_PyBytes_DecodeEscapeRecode(const char **s, const char *end, +- const char *errors, const char *recode_encoding, +- _PyBytesWriter *writer, char *p) +-{ +- PyObject *u, *w; +- const char* t; +- +- t = *s; +- /* Decode non-ASCII bytes as UTF-8. */ +- while (t < end && (*t & 0x80)) +- t++; +- u = PyUnicode_DecodeUTF8(*s, t - *s, errors); +- if (u == NULL) +- return NULL; +- +- /* Recode them in target encoding. */ +- w = PyUnicode_AsEncodedString(u, recode_encoding, errors); +- Py_DECREF(u); +- if (w == NULL) +- return NULL; +- assert(PyBytes_Check(w)); +- +- /* Append bytes to output buffer. */ +- writer->min_size--; /* subtract 1 preallocated byte */ +- p = _PyBytesWriter_WriteBytes(writer, p, +- PyBytes_AS_STRING(w), +- PyBytes_GET_SIZE(w)); +- Py_DECREF(w); +- if (p == NULL) +- return NULL; +- +- *s = t; +- return p; +-} +- +-PyObject *_PyBytes_DecodeEscape(const char *s, +- Py_ssize_t len, +- const char *errors, +- Py_ssize_t unicode, +- const char *recode_encoding, +- const char **first_invalid_escape) +-{ +- int c; +- char *p; +- const char *end; +- _PyBytesWriter writer; +- +- _PyBytesWriter_Init(&writer); +- +- p = _PyBytesWriter_Alloc(&writer, len); +- if (p == NULL) +- return NULL; +- writer.overallocate = 1; +- +- *first_invalid_escape = NULL; +- +- end = s + len; +- while (s < end) { +- if (*s != '\\') { +- non_esc: +- if (!(recode_encoding && (*s & 0x80))) { +- *p++ = *s++; +- } +- else { +- /* non-ASCII character and need to recode */ +- p = _PyBytes_DecodeEscapeRecode(&s, end, +- errors, recode_encoding, +- &writer, p); +- if (p == NULL) +- goto failed; +- } +- continue; +- } +- +- s++; +- if (s == end) { +- PyErr_SetString(PyExc_ValueError, +- "Trailing \\ in string"); +- goto failed; +- } +- +- switch (*s++) { +- /* XXX This assumes ASCII! */ +- case '\n': break; +- case '\\': *p++ = '\\'; break; +- case '\'': *p++ = '\''; break; +- case '\"': *p++ = '\"'; break; +- case 'b': *p++ = '\b'; break; +- case 'f': *p++ = '\014'; break; /* FF */ +- case 't': *p++ = '\t'; break; +- case 'n': *p++ = '\n'; break; +- case 'r': *p++ = '\r'; break; +- case 'v': *p++ = '\013'; break; /* VT */ +- case 'a': *p++ = '\007'; break; /* BEL, not classic C */ +- case '0': case '1': case '2': case '3': +- case '4': case '5': case '6': case '7': +- c = s[-1] - '0'; +- if (s < end && '0' <= *s && *s <= '7') { +- c = (c<<3) + *s++ - '0'; +- if (s < end && '0' <= *s && *s <= '7') +- c = (c<<3) + *s++ - '0'; +- } +- *p++ = c; +- break; +- case 'x': +- if (s+1 < end) { +- int digit1, digit2; +- digit1 = _PyLong_DigitValue[Py_CHARMASK(s[0])]; +- digit2 = _PyLong_DigitValue[Py_CHARMASK(s[1])]; +- if (digit1 < 16 && digit2 < 16) { +- *p++ = (unsigned char)((digit1 << 4) + digit2); +- s += 2; +- break; +- } +- } +- /* invalid hexadecimal digits */ +- +- if (!errors || strcmp(errors, "strict") == 0) { +- PyErr_Format(PyExc_ValueError, +- "invalid \\x escape at position %d", +- s - 2 - (end - len)); +- goto failed; +- } +- if (strcmp(errors, "replace") == 0) { +- *p++ = '?'; +- } else if (strcmp(errors, "ignore") == 0) +- /* do nothing */; +- else { +- PyErr_Format(PyExc_ValueError, +- "decoding error; unknown " +- "error handling code: %.400s", +- errors); +- goto failed; +- } +- /* skip \x */ +- if (s < end && Py_ISXDIGIT(s[0])) +- s++; /* and a hexdigit */ +- break; +- +- default: +- if (*first_invalid_escape == NULL) { +- *first_invalid_escape = s-1; /* Back up one char, since we've +- already incremented s. */ +- } +- *p++ = '\\'; +- s--; +- goto non_esc; /* an arbitrary number of unescaped +- UTF-8 bytes may follow. */ +- } +- } +- +- return _PyBytesWriter_Finish(&writer, p); +- +- failed: +- _PyBytesWriter_Dealloc(&writer); +- return NULL; +-} +- +-PyObject *PyBytes_DecodeEscape(const char *s, +- Py_ssize_t len, +- const char *errors, +- Py_ssize_t unicode, +- const char *recode_encoding) +-{ +- const char* first_invalid_escape; +- PyObject *result = _PyBytes_DecodeEscape(s, len, errors, unicode, +- recode_encoding, +- &first_invalid_escape); +- if (result == NULL) +- return NULL; +- if (first_invalid_escape != NULL) { +- if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, +- "invalid escape sequence '\\%c'", +- (unsigned char)*first_invalid_escape) < 0) { +- Py_DECREF(result); +- return NULL; +- } +- } +- return result; +- +-} +-/* -------------------------------------------------------------------- */ +-/* object api */ +- +-Py_ssize_t +-PyBytes_Size(PyObject *op) +-{ +- if (!PyBytes_Check(op)) { +- PyErr_Format(PyExc_TypeError, +- "expected bytes, %.200s found", Py_TYPE(op)->tp_name); +- return -1; +- } +- return Py_SIZE(op); +-} +- +-char * +-PyBytes_AsString(PyObject *op) +-{ +- if (!PyBytes_Check(op)) { +- PyErr_Format(PyExc_TypeError, +- "expected bytes, %.200s found", Py_TYPE(op)->tp_name); +- return NULL; +- } +- return ((PyBytesObject *)op)->ob_sval; +-} +- +-int +-PyBytes_AsStringAndSize(PyObject *obj, +- char **s, +- Py_ssize_t *len) +-{ +- if (s == NULL) { +- PyErr_BadInternalCall(); +- return -1; +- } +- +- if (!PyBytes_Check(obj)) { +- PyErr_Format(PyExc_TypeError, +- "expected bytes, %.200s found", Py_TYPE(obj)->tp_name); +- return -1; +- } +- +- *s = PyBytes_AS_STRING(obj); +- if (len != NULL) +- *len = PyBytes_GET_SIZE(obj); +- else if (strlen(*s) != (size_t)PyBytes_GET_SIZE(obj)) { +- PyErr_SetString(PyExc_ValueError, +- "embedded null byte"); +- return -1; +- } +- return 0; +-} +- +-/* -------------------------------------------------------------------- */ +-/* Methods */ +- +-#include "stringlib/stringdefs.h" +- +-#include "stringlib/fastsearch.h" +-#include "stringlib/count.h" +-#include "stringlib/find.h" +-#include "stringlib/join.h" +-#include "stringlib/partition.h" +-#include "stringlib/split.h" +-#include "stringlib/ctype.h" +- +-#include "stringlib/transmogrify.h" +- +-PyObject * +-PyBytes_Repr(PyObject *obj, int smartquotes) +-{ +- PyBytesObject* op = (PyBytesObject*) obj; +- Py_ssize_t i, length = Py_SIZE(op); +- Py_ssize_t newsize, squotes, dquotes; +- PyObject *v; +- unsigned char quote, *s, *p; +- +- /* Compute size of output string */ +- squotes = dquotes = 0; +- newsize = 3; /* b'' */ +- s = (unsigned char*)op->ob_sval; +- for (i = 0; i < length; i++) { +- Py_ssize_t incr = 1; +- switch(s[i]) { +- case '\'': squotes++; break; +- case '"': dquotes++; break; +- case '\\': case '\t': case '\n': case '\r': +- incr = 2; break; /* \C */ +- default: +- if (s[i] < ' ' || s[i] >= 0x7f) +- incr = 4; /* \xHH */ +- } +- if (newsize > PY_SSIZE_T_MAX - incr) +- goto overflow; +- newsize += incr; +- } +- quote = '\''; +- if (smartquotes && squotes && !dquotes) +- quote = '"'; +- if (squotes && quote == '\'') { +- if (newsize > PY_SSIZE_T_MAX - squotes) +- goto overflow; +- newsize += squotes; +- } +- +- v = PyUnicode_New(newsize, 127); +- if (v == NULL) { +- return NULL; +- } +- p = PyUnicode_1BYTE_DATA(v); +- +- *p++ = 'b', *p++ = quote; +- for (i = 0; i < length; i++) { +- unsigned char c = op->ob_sval[i]; +- if (c == quote || c == '\\') +- *p++ = '\\', *p++ = c; +- else if (c == '\t') +- *p++ = '\\', *p++ = 't'; +- else if (c == '\n') +- *p++ = '\\', *p++ = 'n'; +- else if (c == '\r') +- *p++ = '\\', *p++ = 'r'; +- else if (c < ' ' || c >= 0x7f) { +- *p++ = '\\'; +- *p++ = 'x'; +- *p++ = Py_hexdigits[(c & 0xf0) >> 4]; +- *p++ = Py_hexdigits[c & 0xf]; +- } +- else +- *p++ = c; +- } +- *p++ = quote; +- assert(_PyUnicode_CheckConsistency(v, 1)); +- return v; +- +- overflow: +- PyErr_SetString(PyExc_OverflowError, +- "bytes object is too large to make repr"); +- return NULL; +-} +- +-static PyObject * +-bytes_repr(PyObject *op) +-{ +- return PyBytes_Repr(op, 1); +-} +- +-static PyObject * +-bytes_str(PyObject *op) +-{ +- if (Py_BytesWarningFlag) { +- if (PyErr_WarnEx(PyExc_BytesWarning, +- "str() on a bytes instance", 1)) +- return NULL; +- } +- return bytes_repr(op); +-} +- +-static Py_ssize_t +-bytes_length(PyBytesObject *a) +-{ +- return Py_SIZE(a); +-} +- +-/* This is also used by PyBytes_Concat() */ +-static PyObject * +-bytes_concat(PyObject *a, PyObject *b) +-{ +- Py_buffer va, vb; +- PyObject *result = NULL; +- +- va.len = -1; +- vb.len = -1; +- if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 || +- PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) { +- PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", +- Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name); +- goto done; +- } +- +- /* Optimize end cases */ +- if (va.len == 0 && PyBytes_CheckExact(b)) { +- result = b; +- Py_INCREF(result); +- goto done; +- } +- if (vb.len == 0 && PyBytes_CheckExact(a)) { +- result = a; +- Py_INCREF(result); +- goto done; +- } +- +- if (va.len > PY_SSIZE_T_MAX - vb.len) { +- PyErr_NoMemory(); +- goto done; +- } +- +- result = PyBytes_FromStringAndSize(NULL, va.len + vb.len); +- if (result != NULL) { +- memcpy(PyBytes_AS_STRING(result), va.buf, va.len); +- memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len); +- } +- +- done: +- if (va.len != -1) +- PyBuffer_Release(&va); +- if (vb.len != -1) +- PyBuffer_Release(&vb); +- return result; +-} +- +-static PyObject * +-bytes_repeat(PyBytesObject *a, Py_ssize_t n) +-{ +- Py_ssize_t i; +- Py_ssize_t j; +- Py_ssize_t size; +- PyBytesObject *op; +- size_t nbytes; +- if (n < 0) +- n = 0; +- /* watch out for overflows: the size can overflow int, +- * and the # of bytes needed can overflow size_t +- */ +- if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n) { +- PyErr_SetString(PyExc_OverflowError, +- "repeated bytes are too long"); +- return NULL; +- } +- size = Py_SIZE(a) * n; +- if (size == Py_SIZE(a) && PyBytes_CheckExact(a)) { +- Py_INCREF(a); +- return (PyObject *)a; +- } +- nbytes = (size_t)size; +- if (nbytes + PyBytesObject_SIZE <= nbytes) { +- PyErr_SetString(PyExc_OverflowError, +- "repeated bytes are too long"); +- return NULL; +- } +- op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + nbytes); +- if (op == NULL) +- return PyErr_NoMemory(); +- (void)PyObject_INIT_VAR(op, &PyBytes_Type, size); +- op->ob_shash = -1; +- op->ob_sval[size] = '\0'; +- if (Py_SIZE(a) == 1 && n > 0) { +- memset(op->ob_sval, a->ob_sval[0] , n); +- return (PyObject *) op; +- } +- i = 0; +- if (i < size) { +- memcpy(op->ob_sval, a->ob_sval, Py_SIZE(a)); +- i = Py_SIZE(a); +- } +- while (i < size) { +- j = (i <= size-i) ? i : size-i; +- memcpy(op->ob_sval+i, op->ob_sval, j); +- i += j; +- } +- return (PyObject *) op; +-} +- +-static int +-bytes_contains(PyObject *self, PyObject *arg) +-{ +- return _Py_bytes_contains(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), arg); +-} +- +-static PyObject * +-bytes_item(PyBytesObject *a, Py_ssize_t i) +-{ +- if (i < 0 || i >= Py_SIZE(a)) { +- PyErr_SetString(PyExc_IndexError, "index out of range"); +- return NULL; +- } +- return PyLong_FromLong((unsigned char)a->ob_sval[i]); +-} +- +-static int +-bytes_compare_eq(PyBytesObject *a, PyBytesObject *b) +-{ +- int cmp; +- Py_ssize_t len; +- +- len = Py_SIZE(a); +- if (Py_SIZE(b) != len) +- return 0; +- +- if (a->ob_sval[0] != b->ob_sval[0]) +- return 0; +- +- cmp = memcmp(a->ob_sval, b->ob_sval, len); +- return (cmp == 0); +-} +- +-static PyObject* +-bytes_richcompare(PyBytesObject *a, PyBytesObject *b, int op) +-{ +- int c; +- Py_ssize_t len_a, len_b; +- Py_ssize_t min_len; +- PyObject *result; +- int rc; +- +- /* Make sure both arguments are strings. */ +- if (!(PyBytes_Check(a) && PyBytes_Check(b))) { +- if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) { +- rc = PyObject_IsInstance((PyObject*)a, +- (PyObject*)&PyUnicode_Type); +- if (!rc) +- rc = PyObject_IsInstance((PyObject*)b, +- (PyObject*)&PyUnicode_Type); +- if (rc < 0) +- return NULL; +- if (rc) { +- if (PyErr_WarnEx(PyExc_BytesWarning, +- "Comparison between bytes and string", 1)) +- return NULL; +- } +- else { +- rc = PyObject_IsInstance((PyObject*)a, +- (PyObject*)&PyLong_Type); +- if (!rc) +- rc = PyObject_IsInstance((PyObject*)b, +- (PyObject*)&PyLong_Type); +- if (rc < 0) +- return NULL; +- if (rc) { +- if (PyErr_WarnEx(PyExc_BytesWarning, +- "Comparison between bytes and int", 1)) +- return NULL; +- } +- } +- } +- result = Py_NotImplemented; +- } +- else if (a == b) { +- switch (op) { +- case Py_EQ: +- case Py_LE: +- case Py_GE: +- /* a string is equal to itself */ +- result = Py_True; +- break; +- case Py_NE: +- case Py_LT: +- case Py_GT: +- result = Py_False; +- break; +- default: +- PyErr_BadArgument(); +- return NULL; +- } +- } +- else if (op == Py_EQ || op == Py_NE) { +- int eq = bytes_compare_eq(a, b); +- eq ^= (op == Py_NE); +- result = eq ? Py_True : Py_False; +- } +- else { +- len_a = Py_SIZE(a); +- len_b = Py_SIZE(b); +- min_len = Py_MIN(len_a, len_b); +- if (min_len > 0) { +- c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval); +- if (c == 0) +- c = memcmp(a->ob_sval, b->ob_sval, min_len); +- } +- else +- c = 0; +- if (c == 0) +- c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; +- switch (op) { +- case Py_LT: c = c < 0; break; +- case Py_LE: c = c <= 0; break; +- case Py_GT: c = c > 0; break; +- case Py_GE: c = c >= 0; break; +- default: +- PyErr_BadArgument(); +- return NULL; +- } +- result = c ? Py_True : Py_False; +- } +- +- Py_INCREF(result); +- return result; +-} +- +-static Py_hash_t +-bytes_hash(PyBytesObject *a) +-{ +- if (a->ob_shash == -1) { +- /* Can't fail */ +- a->ob_shash = _Py_HashBytes(a->ob_sval, Py_SIZE(a)); +- } +- return a->ob_shash; +-} +- +-static PyObject* +-bytes_subscript(PyBytesObject* self, PyObject* item) +-{ +- if (PyIndex_Check(item)) { +- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); +- if (i == -1 && PyErr_Occurred()) +- return NULL; +- if (i < 0) +- i += PyBytes_GET_SIZE(self); +- if (i < 0 || i >= PyBytes_GET_SIZE(self)) { +- PyErr_SetString(PyExc_IndexError, +- "index out of range"); +- return NULL; +- } +- return PyLong_FromLong((unsigned char)self->ob_sval[i]); +- } +- else if (PySlice_Check(item)) { +- Py_ssize_t start, stop, step, slicelength, cur, i; +- char* source_buf; +- char* result_buf; +- PyObject* result; +- +- if (PySlice_Unpack(item, &start, &stop, &step) < 0) { +- return NULL; +- } +- slicelength = PySlice_AdjustIndices(PyBytes_GET_SIZE(self), &start, +- &stop, step); +- +- if (slicelength <= 0) { +- return PyBytes_FromStringAndSize("", 0); +- } +- else if (start == 0 && step == 1 && +- slicelength == PyBytes_GET_SIZE(self) && +- PyBytes_CheckExact(self)) { +- Py_INCREF(self); +- return (PyObject *)self; +- } +- else if (step == 1) { +- return PyBytes_FromStringAndSize( +- PyBytes_AS_STRING(self) + start, +- slicelength); +- } +- else { +- source_buf = PyBytes_AS_STRING(self); +- result = PyBytes_FromStringAndSize(NULL, slicelength); +- if (result == NULL) +- return NULL; +- +- result_buf = PyBytes_AS_STRING(result); +- for (cur = start, i = 0; i < slicelength; +- cur += step, i++) { +- result_buf[i] = source_buf[cur]; +- } +- +- return result; +- } +- } +- else { +- PyErr_Format(PyExc_TypeError, +- "byte indices must be integers or slices, not %.200s", +- Py_TYPE(item)->tp_name); +- return NULL; +- } +-} +- +-static int +-bytes_buffer_getbuffer(PyBytesObject *self, Py_buffer *view, int flags) +-{ +- return PyBuffer_FillInfo(view, (PyObject*)self, (void *)self->ob_sval, Py_SIZE(self), +- 1, flags); +-} +- +-static PySequenceMethods bytes_as_sequence = { +- (lenfunc)bytes_length, /*sq_length*/ +- (binaryfunc)bytes_concat, /*sq_concat*/ +- (ssizeargfunc)bytes_repeat, /*sq_repeat*/ +- (ssizeargfunc)bytes_item, /*sq_item*/ +- 0, /*sq_slice*/ +- 0, /*sq_ass_item*/ +- 0, /*sq_ass_slice*/ +- (objobjproc)bytes_contains /*sq_contains*/ +-}; +- +-static PyMappingMethods bytes_as_mapping = { +- (lenfunc)bytes_length, +- (binaryfunc)bytes_subscript, +- 0, +-}; +- +-static PyBufferProcs bytes_as_buffer = { +- (getbufferproc)bytes_buffer_getbuffer, +- NULL, +-}; +- +- +-#define LEFTSTRIP 0 +-#define RIGHTSTRIP 1 +-#define BOTHSTRIP 2 +- +-/*[clinic input] +-bytes.split +- +- sep: object = None +- The delimiter according which to split the bytes. +- None (the default value) means split on ASCII whitespace characters +- (space, tab, return, newline, formfeed, vertical tab). +- maxsplit: Py_ssize_t = -1 +- Maximum number of splits to do. +- -1 (the default value) means no limit. +- +-Return a list of the sections in the bytes, using sep as the delimiter. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_split_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit) +-/*[clinic end generated code: output=52126b5844c1d8ef input=8b809b39074abbfa]*/ +-{ +- Py_ssize_t len = PyBytes_GET_SIZE(self), n; +- const char *s = PyBytes_AS_STRING(self), *sub; +- Py_buffer vsub; +- PyObject *list; +- +- if (maxsplit < 0) +- maxsplit = PY_SSIZE_T_MAX; +- if (sep == Py_None) +- return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit); +- if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) +- return NULL; +- sub = vsub.buf; +- n = vsub.len; +- +- list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit); +- PyBuffer_Release(&vsub); +- return list; +-} +- +-/*[clinic input] +-bytes.partition +- +- sep: Py_buffer +- / +- +-Partition the bytes into three parts using the given separator. +- +-This will search for the separator sep in the bytes. If the separator is found, +-returns a 3-tuple containing the part before the separator, the separator +-itself, and the part after it. +- +-If the separator is not found, returns a 3-tuple containing the original bytes +-object and two empty bytes objects. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_partition_impl(PyBytesObject *self, Py_buffer *sep) +-/*[clinic end generated code: output=f532b392a17ff695 input=61cca95519406099]*/ +-{ +- return stringlib_partition( +- (PyObject*) self, +- PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), +- sep->obj, (const char *)sep->buf, sep->len +- ); +-} +- +-/*[clinic input] +-bytes.rpartition +- +- sep: Py_buffer +- / +- +-Partition the bytes into three parts using the given separator. +- +-This will search for the separator sep in the bytes, starting at the end. If +-the separator is found, returns a 3-tuple containing the part before the +-separator, the separator itself, and the part after it. +- +-If the separator is not found, returns a 3-tuple containing two empty bytes +-objects and the original bytes object. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_rpartition_impl(PyBytesObject *self, Py_buffer *sep) +-/*[clinic end generated code: output=191b114cbb028e50 input=d78db010c8cfdbe1]*/ +-{ +- return stringlib_rpartition( +- (PyObject*) self, +- PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), +- sep->obj, (const char *)sep->buf, sep->len +- ); +-} +- +-/*[clinic input] +-bytes.rsplit = bytes.split +- +-Return a list of the sections in the bytes, using sep as the delimiter. +- +-Splitting is done starting at the end of the bytes and working to the front. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_rsplit_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit) +-/*[clinic end generated code: output=ba698d9ea01e1c8f input=0f86c9f28f7d7b7b]*/ +-{ +- Py_ssize_t len = PyBytes_GET_SIZE(self), n; +- const char *s = PyBytes_AS_STRING(self), *sub; +- Py_buffer vsub; +- PyObject *list; +- +- if (maxsplit < 0) +- maxsplit = PY_SSIZE_T_MAX; +- if (sep == Py_None) +- return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit); +- if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) +- return NULL; +- sub = vsub.buf; +- n = vsub.len; +- +- list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit); +- PyBuffer_Release(&vsub); +- return list; +-} +- +- +-/*[clinic input] +-bytes.join +- +- iterable_of_bytes: object +- / +- +-Concatenate any number of bytes objects. +- +-The bytes whose method is called is inserted in between each pair. +- +-The result is returned as a new bytes object. +- +-Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_join(PyBytesObject *self, PyObject *iterable_of_bytes) +-/*[clinic end generated code: output=a046f379f626f6f8 input=7fe377b95bd549d2]*/ +-{ +- return stringlib_bytes_join((PyObject*)self, iterable_of_bytes); +-} +- +-PyObject * +-_PyBytes_Join(PyObject *sep, PyObject *x) +-{ +- assert(sep != NULL && PyBytes_Check(sep)); +- assert(x != NULL); +- return bytes_join((PyBytesObject*)sep, x); +-} +- +-static PyObject * +-bytes_find(PyBytesObject *self, PyObject *args) +-{ +- return _Py_bytes_find(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); +-} +- +-static PyObject * +-bytes_index(PyBytesObject *self, PyObject *args) +-{ +- return _Py_bytes_index(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); +-} +- +- +-static PyObject * +-bytes_rfind(PyBytesObject *self, PyObject *args) +-{ +- return _Py_bytes_rfind(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); +-} +- +- +-static PyObject * +-bytes_rindex(PyBytesObject *self, PyObject *args) +-{ +- return _Py_bytes_rindex(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); +-} +- +- +-Py_LOCAL_INLINE(PyObject *) +-do_xstrip(PyBytesObject *self, int striptype, PyObject *sepobj) +-{ +- Py_buffer vsep; +- char *s = PyBytes_AS_STRING(self); +- Py_ssize_t len = PyBytes_GET_SIZE(self); +- char *sep; +- Py_ssize_t seplen; +- Py_ssize_t i, j; +- +- if (PyObject_GetBuffer(sepobj, &vsep, PyBUF_SIMPLE) != 0) +- return NULL; +- sep = vsep.buf; +- seplen = vsep.len; +- +- i = 0; +- if (striptype != RIGHTSTRIP) { +- while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) { +- i++; +- } +- } +- +- j = len; +- if (striptype != LEFTSTRIP) { +- do { +- j--; +- } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen)); +- j++; +- } +- +- PyBuffer_Release(&vsep); +- +- if (i == 0 && j == len && PyBytes_CheckExact(self)) { +- Py_INCREF(self); +- return (PyObject*)self; +- } +- else +- return PyBytes_FromStringAndSize(s+i, j-i); +-} +- +- +-Py_LOCAL_INLINE(PyObject *) +-do_strip(PyBytesObject *self, int striptype) +-{ +- char *s = PyBytes_AS_STRING(self); +- Py_ssize_t len = PyBytes_GET_SIZE(self), i, j; +- +- i = 0; +- if (striptype != RIGHTSTRIP) { +- while (i < len && Py_ISSPACE(s[i])) { +- i++; +- } +- } +- +- j = len; +- if (striptype != LEFTSTRIP) { +- do { +- j--; +- } while (j >= i && Py_ISSPACE(s[j])); +- j++; +- } +- +- if (i == 0 && j == len && PyBytes_CheckExact(self)) { +- Py_INCREF(self); +- return (PyObject*)self; +- } +- else +- return PyBytes_FromStringAndSize(s+i, j-i); +-} +- +- +-Py_LOCAL_INLINE(PyObject *) +-do_argstrip(PyBytesObject *self, int striptype, PyObject *bytes) +-{ +- if (bytes != NULL && bytes != Py_None) { +- return do_xstrip(self, striptype, bytes); +- } +- return do_strip(self, striptype); +-} +- +-/*[clinic input] +-bytes.strip +- +- bytes: object = None +- / +- +-Strip leading and trailing bytes contained in the argument. +- +-If the argument is omitted or None, strip leading and trailing ASCII whitespace. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_strip_impl(PyBytesObject *self, PyObject *bytes) +-/*[clinic end generated code: output=c7c228d3bd104a1b input=8a354640e4e0b3ef]*/ +-{ +- return do_argstrip(self, BOTHSTRIP, bytes); +-} +- +-/*[clinic input] +-bytes.lstrip +- +- bytes: object = None +- / +- +-Strip leading bytes contained in the argument. +- +-If the argument is omitted or None, strip leading ASCII whitespace. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_lstrip_impl(PyBytesObject *self, PyObject *bytes) +-/*[clinic end generated code: output=28602e586f524e82 input=9baff4398c3f6857]*/ +-{ +- return do_argstrip(self, LEFTSTRIP, bytes); +-} +- +-/*[clinic input] +-bytes.rstrip +- +- bytes: object = None +- / +- +-Strip trailing bytes contained in the argument. +- +-If the argument is omitted or None, strip trailing ASCII whitespace. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_rstrip_impl(PyBytesObject *self, PyObject *bytes) +-/*[clinic end generated code: output=547e3815c95447da input=b78af445c727e32b]*/ +-{ +- return do_argstrip(self, RIGHTSTRIP, bytes); +-} +- +- +-static PyObject * +-bytes_count(PyBytesObject *self, PyObject *args) +-{ +- return _Py_bytes_count(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); +-} +- +- +-/*[clinic input] +-bytes.translate +- +- table: object +- Translation table, which must be a bytes object of length 256. +- / +- delete as deletechars: object(c_default="NULL") = b'' +- +-Return a copy with each character mapped by the given translation table. +- +-All characters occurring in the optional argument delete are removed. +-The remaining characters are mapped through the given translation table. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_translate_impl(PyBytesObject *self, PyObject *table, +- PyObject *deletechars) +-/*[clinic end generated code: output=43be3437f1956211 input=0ecdf159f654233c]*/ +-{ +- char *input, *output; +- Py_buffer table_view = {NULL, NULL}; +- Py_buffer del_table_view = {NULL, NULL}; +- const char *table_chars; +- Py_ssize_t i, c, changed = 0; +- PyObject *input_obj = (PyObject*)self; +- const char *output_start, *del_table_chars=NULL; +- Py_ssize_t inlen, tablen, dellen = 0; +- PyObject *result; +- int trans_table[256]; +- +- if (PyBytes_Check(table)) { +- table_chars = PyBytes_AS_STRING(table); +- tablen = PyBytes_GET_SIZE(table); +- } +- else if (table == Py_None) { +- table_chars = NULL; +- tablen = 256; +- } +- else { +- if (PyObject_GetBuffer(table, &table_view, PyBUF_SIMPLE) != 0) +- return NULL; +- table_chars = table_view.buf; +- tablen = table_view.len; +- } +- +- if (tablen != 256) { +- PyErr_SetString(PyExc_ValueError, +- "translation table must be 256 characters long"); +- PyBuffer_Release(&table_view); +- return NULL; +- } +- +- if (deletechars != NULL) { +- if (PyBytes_Check(deletechars)) { +- del_table_chars = PyBytes_AS_STRING(deletechars); +- dellen = PyBytes_GET_SIZE(deletechars); +- } +- else { +- if (PyObject_GetBuffer(deletechars, &del_table_view, PyBUF_SIMPLE) != 0) { +- PyBuffer_Release(&table_view); +- return NULL; +- } +- del_table_chars = del_table_view.buf; +- dellen = del_table_view.len; +- } +- } +- else { +- del_table_chars = NULL; +- dellen = 0; +- } +- +- inlen = PyBytes_GET_SIZE(input_obj); +- result = PyBytes_FromStringAndSize((char *)NULL, inlen); +- if (result == NULL) { +- PyBuffer_Release(&del_table_view); +- PyBuffer_Release(&table_view); +- return NULL; +- } +- output_start = output = PyBytes_AS_STRING(result); +- input = PyBytes_AS_STRING(input_obj); +- +- if (dellen == 0 && table_chars != NULL) { +- /* If no deletions are required, use faster code */ +- for (i = inlen; --i >= 0; ) { +- c = Py_CHARMASK(*input++); +- if (Py_CHARMASK((*output++ = table_chars[c])) != c) +- changed = 1; +- } +- if (!changed && PyBytes_CheckExact(input_obj)) { +- Py_INCREF(input_obj); +- Py_DECREF(result); +- result = input_obj; +- } +- PyBuffer_Release(&del_table_view); +- PyBuffer_Release(&table_view); +- return result; +- } +- +- if (table_chars == NULL) { +- for (i = 0; i < 256; i++) +- trans_table[i] = Py_CHARMASK(i); +- } else { +- for (i = 0; i < 256; i++) +- trans_table[i] = Py_CHARMASK(table_chars[i]); +- } +- PyBuffer_Release(&table_view); +- +- for (i = 0; i < dellen; i++) +- trans_table[(int) Py_CHARMASK(del_table_chars[i])] = -1; +- PyBuffer_Release(&del_table_view); +- +- for (i = inlen; --i >= 0; ) { +- c = Py_CHARMASK(*input++); +- if (trans_table[c] != -1) +- if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c) +- continue; +- changed = 1; +- } +- if (!changed && PyBytes_CheckExact(input_obj)) { +- Py_DECREF(result); +- Py_INCREF(input_obj); +- return input_obj; +- } +- /* Fix the size of the resulting string */ +- if (inlen > 0) +- _PyBytes_Resize(&result, output - output_start); +- return result; +-} +- +- +-/*[clinic input] +- +-@staticmethod +-bytes.maketrans +- +- frm: Py_buffer +- to: Py_buffer +- / +- +-Return a translation table useable for the bytes or bytearray translate method. +- +-The returned table will be one where each byte in frm is mapped to the byte at +-the same position in to. +- +-The bytes objects frm and to must be of the same length. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_maketrans_impl(Py_buffer *frm, Py_buffer *to) +-/*[clinic end generated code: output=a36f6399d4b77f6f input=de7a8fc5632bb8f1]*/ +-{ +- return _Py_bytes_maketrans(frm, to); +-} +- +- +-/*[clinic input] +-bytes.replace +- +- old: Py_buffer +- new: Py_buffer +- count: Py_ssize_t = -1 +- Maximum number of occurrences to replace. +- -1 (the default value) means replace all occurrences. +- / +- +-Return a copy with all occurrences of substring old replaced by new. +- +-If the optional argument count is given, only the first count occurrences are +-replaced. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_replace_impl(PyBytesObject *self, Py_buffer *old, Py_buffer *new, +- Py_ssize_t count) +-/*[clinic end generated code: output=994fa588b6b9c104 input=b2fbbf0bf04de8e5]*/ +-{ +- return stringlib_replace((PyObject *)self, +- (const char *)old->buf, old->len, +- (const char *)new->buf, new->len, count); +-} +- +-/** End DALKE **/ +- +- +-static PyObject * +-bytes_startswith(PyBytesObject *self, PyObject *args) +-{ +- return _Py_bytes_startswith(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); +-} +- +-static PyObject * +-bytes_endswith(PyBytesObject *self, PyObject *args) +-{ +- return _Py_bytes_endswith(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); +-} +- +- +-/*[clinic input] +-bytes.decode +- +- encoding: str(c_default="NULL") = 'utf-8' +- The encoding with which to decode the bytes. +- errors: str(c_default="NULL") = 'strict' +- The error handling scheme to use for the handling of decoding errors. +- The default is 'strict' meaning that decoding errors raise a +- UnicodeDecodeError. Other possible values are 'ignore' and 'replace' +- as well as any other name registered with codecs.register_error that +- can handle UnicodeDecodeErrors. +- +-Decode the bytes using the codec registered for encoding. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_decode_impl(PyBytesObject *self, const char *encoding, +- const char *errors) +-/*[clinic end generated code: output=5649a53dde27b314 input=958174769d2a40ca]*/ +-{ +- return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors); +-} +- +- +-/*[clinic input] +-bytes.splitlines +- +- keepends: bool(accept={int}) = False +- +-Return a list of the lines in the bytes, breaking at line boundaries. +- +-Line breaks are not included in the resulting list unless keepends is given and +-true. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_splitlines_impl(PyBytesObject *self, int keepends) +-/*[clinic end generated code: output=3484149a5d880ffb input=a8b32eb01ff5a5ed]*/ +-{ +- return stringlib_splitlines( +- (PyObject*) self, PyBytes_AS_STRING(self), +- PyBytes_GET_SIZE(self), keepends +- ); +-} +- +-/*[clinic input] +-@classmethod +-bytes.fromhex +- +- string: unicode +- / +- +-Create a bytes object from a string of hexadecimal numbers. +- +-Spaces between two numbers are accepted. +-Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'. +-[clinic start generated code]*/ +- +-static PyObject * +-bytes_fromhex_impl(PyTypeObject *type, PyObject *string) +-/*[clinic end generated code: output=0973acc63661bb2e input=bf4d1c361670acd3]*/ +-{ +- PyObject *result = _PyBytes_FromHex(string, 0); +- if (type != &PyBytes_Type && result != NULL) { +- Py_SETREF(result, PyObject_CallFunctionObjArgs((PyObject *)type, +- result, NULL)); +- } +- return result; +-} +- +-PyObject* +-_PyBytes_FromHex(PyObject *string, int use_bytearray) +-{ +- char *buf; +- Py_ssize_t hexlen, invalid_char; +- unsigned int top, bot; +- Py_UCS1 *str, *end; +- _PyBytesWriter writer; +- +- _PyBytesWriter_Init(&writer); +- writer.use_bytearray = use_bytearray; +- +- assert(PyUnicode_Check(string)); +- if (PyUnicode_READY(string)) +- return NULL; +- hexlen = PyUnicode_GET_LENGTH(string); +- +- if (!PyUnicode_IS_ASCII(string)) { +- void *data = PyUnicode_DATA(string); +- unsigned int kind = PyUnicode_KIND(string); +- Py_ssize_t i; +- +- /* search for the first non-ASCII character */ +- for (i = 0; i < hexlen; i++) { +- if (PyUnicode_READ(kind, data, i) >= 128) +- break; +- } +- invalid_char = i; +- goto error; +- } +- +- assert(PyUnicode_KIND(string) == PyUnicode_1BYTE_KIND); +- str = PyUnicode_1BYTE_DATA(string); +- +- /* This overestimates if there are spaces */ +- buf = _PyBytesWriter_Alloc(&writer, hexlen / 2); +- if (buf == NULL) +- return NULL; +- +- end = str + hexlen; +- while (str < end) { +- /* skip over spaces in the input */ +- if (Py_ISSPACE(*str)) { +- do { +- str++; +- } while (Py_ISSPACE(*str)); +- if (str >= end) +- break; +- } +- +- top = _PyLong_DigitValue[*str]; +- if (top >= 16) { +- invalid_char = str - PyUnicode_1BYTE_DATA(string); +- goto error; +- } +- str++; +- +- bot = _PyLong_DigitValue[*str]; +- if (bot >= 16) { +- invalid_char = str - PyUnicode_1BYTE_DATA(string); +- goto error; +- } +- str++; +- +- *buf++ = (unsigned char)((top << 4) + bot); +- } +- +- return _PyBytesWriter_Finish(&writer, buf); +- +- error: +- PyErr_Format(PyExc_ValueError, +- "non-hexadecimal number found in " +- "fromhex() arg at position %zd", invalid_char); +- _PyBytesWriter_Dealloc(&writer); +- return NULL; +-} +- +-PyDoc_STRVAR(hex__doc__, +-"B.hex() -> string\n\ +-\n\ +-Create a string of hexadecimal numbers from a bytes object.\n\ +-Example: b'\\xb9\\x01\\xef'.hex() -> 'b901ef'."); +- +-static PyObject * +-bytes_hex(PyBytesObject *self) +-{ +- char* argbuf = PyBytes_AS_STRING(self); +- Py_ssize_t arglen = PyBytes_GET_SIZE(self); +- return _Py_strhex(argbuf, arglen); +-} +- +-static PyObject * +-bytes_getnewargs(PyBytesObject *v) +-{ +- return Py_BuildValue("(y#)", v->ob_sval, Py_SIZE(v)); +-} +- +- +-static PyMethodDef +-bytes_methods[] = { +- {"__getnewargs__", (PyCFunction)bytes_getnewargs, METH_NOARGS}, +- {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS, +- _Py_capitalize__doc__}, +- {"center", (PyCFunction)stringlib_center, METH_VARARGS, +- _Py_center__doc__}, +- {"count", (PyCFunction)bytes_count, METH_VARARGS, +- _Py_count__doc__}, +- BYTES_DECODE_METHODDEF +- {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, +- _Py_endswith__doc__}, +- {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS, +- _Py_expandtabs__doc__}, +- {"find", (PyCFunction)bytes_find, METH_VARARGS, +- _Py_find__doc__}, +- BYTES_FROMHEX_METHODDEF +- {"hex", (PyCFunction)bytes_hex, METH_NOARGS, hex__doc__}, +- {"index", (PyCFunction)bytes_index, METH_VARARGS, _Py_index__doc__}, +- {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS, +- _Py_isalnum__doc__}, +- {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS, +- _Py_isalpha__doc__}, +- {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS, +- _Py_isdigit__doc__}, +- {"islower", (PyCFunction)stringlib_islower, METH_NOARGS, +- _Py_islower__doc__}, +- {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS, +- _Py_isspace__doc__}, +- {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS, +- _Py_istitle__doc__}, +- {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS, +- _Py_isupper__doc__}, +- BYTES_JOIN_METHODDEF +- {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, _Py_ljust__doc__}, +- {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__}, +- BYTES_LSTRIP_METHODDEF +- BYTES_MAKETRANS_METHODDEF +- BYTES_PARTITION_METHODDEF +- BYTES_REPLACE_METHODDEF +- {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, _Py_rfind__doc__}, +- {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, _Py_rindex__doc__}, +- {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, _Py_rjust__doc__}, +- BYTES_RPARTITION_METHODDEF +- BYTES_RSPLIT_METHODDEF +- BYTES_RSTRIP_METHODDEF +- BYTES_SPLIT_METHODDEF +- BYTES_SPLITLINES_METHODDEF +- {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS, +- _Py_startswith__doc__}, +- BYTES_STRIP_METHODDEF +- {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS, +- _Py_swapcase__doc__}, +- {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__}, +- BYTES_TRANSLATE_METHODDEF +- {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__}, +- {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, _Py_zfill__doc__}, +- {NULL, NULL} /* sentinel */ +-}; +- +-static PyObject * +-bytes_mod(PyObject *self, PyObject *arg) +-{ +- if (!PyBytes_Check(self)) { +- Py_RETURN_NOTIMPLEMENTED; +- } +- return _PyBytes_FormatEx(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), +- arg, 0); +-} +- +-static PyNumberMethods bytes_as_number = { +- 0, /*nb_add*/ +- 0, /*nb_subtract*/ +- 0, /*nb_multiply*/ +- bytes_mod, /*nb_remainder*/ +-}; +- +-static PyObject * +-bytes_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds); +- +-static PyObject * +-bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +-{ +- PyObject *x = NULL; +- const char *encoding = NULL; +- const char *errors = NULL; +- PyObject *new = NULL; +- PyObject *func; +- Py_ssize_t size; +- static char *kwlist[] = {"source", "encoding", "errors", 0}; +- _Py_IDENTIFIER(__bytes__); +- +- if (type != &PyBytes_Type) +- return bytes_subtype_new(type, args, kwds); +- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytes", kwlist, &x, +- &encoding, &errors)) +- return NULL; +- if (x == NULL) { +- if (encoding != NULL || errors != NULL) { +- PyErr_SetString(PyExc_TypeError, +- "encoding or errors without sequence " +- "argument"); +- return NULL; +- } +- return PyBytes_FromStringAndSize(NULL, 0); +- } +- +- if (encoding != NULL) { +- /* Encode via the codec registry */ +- if (!PyUnicode_Check(x)) { +- PyErr_SetString(PyExc_TypeError, +- "encoding without a string argument"); +- return NULL; +- } +- new = PyUnicode_AsEncodedString(x, encoding, errors); +- if (new == NULL) +- return NULL; +- assert(PyBytes_Check(new)); +- return new; +- } +- +- if (errors != NULL) { +- PyErr_SetString(PyExc_TypeError, +- PyUnicode_Check(x) ? +- "string argument without an encoding" : +- "errors without a string argument"); +- return NULL; +- } +- +- /* We'd like to call PyObject_Bytes here, but we need to check for an +- integer argument before deferring to PyBytes_FromObject, something +- PyObject_Bytes doesn't do. */ +- func = _PyObject_LookupSpecial(x, &PyId___bytes__); +- if (func != NULL) { +- new = _PyObject_CallNoArg(func); +- Py_DECREF(func); +- if (new == NULL) +- return NULL; +- if (!PyBytes_Check(new)) { +- PyErr_Format(PyExc_TypeError, +- "__bytes__ returned non-bytes (type %.200s)", +- Py_TYPE(new)->tp_name); +- Py_DECREF(new); +- return NULL; +- } +- return new; +- } +- else if (PyErr_Occurred()) +- return NULL; +- +- if (PyUnicode_Check(x)) { +- PyErr_SetString(PyExc_TypeError, +- "string argument without an encoding"); +- return NULL; +- } +- /* Is it an integer? */ +- if (PyIndex_Check(x)) { +- size = PyNumber_AsSsize_t(x, PyExc_OverflowError); +- if (size == -1 && PyErr_Occurred()) { +- if (PyErr_ExceptionMatches(PyExc_OverflowError)) +- return NULL; +- PyErr_Clear(); /* fall through */ +- } +- else { +- if (size < 0) { +- PyErr_SetString(PyExc_ValueError, "negative count"); +- return NULL; +- } +- new = _PyBytes_FromSize(size, 1); +- if (new == NULL) +- return NULL; +- return new; +- } +- } +- +- return PyBytes_FromObject(x); +-} +- +-static PyObject* +-_PyBytes_FromBuffer(PyObject *x) +-{ +- PyObject *new; +- Py_buffer view; +- +- if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0) +- return NULL; +- +- new = PyBytes_FromStringAndSize(NULL, view.len); +- if (!new) +- goto fail; +- if (PyBuffer_ToContiguous(((PyBytesObject *)new)->ob_sval, +- &view, view.len, 'C') < 0) +- goto fail; +- PyBuffer_Release(&view); +- return new; +- +-fail: +- Py_XDECREF(new); +- PyBuffer_Release(&view); +- return NULL; +-} +- +-#define _PyBytes_FROM_LIST_BODY(x, GET_ITEM) \ +- do { \ +- PyObject *bytes; \ +- Py_ssize_t i; \ +- Py_ssize_t value; \ +- char *str; \ +- PyObject *item; \ +- \ +- bytes = PyBytes_FromStringAndSize(NULL, Py_SIZE(x)); \ +- if (bytes == NULL) \ +- return NULL; \ +- str = ((PyBytesObject *)bytes)->ob_sval; \ +- \ +- for (i = 0; i < Py_SIZE(x); i++) { \ +- item = GET_ITEM((x), i); \ +- value = PyNumber_AsSsize_t(item, NULL); \ +- if (value == -1 && PyErr_Occurred()) \ +- goto error; \ +- \ +- if (value < 0 || value >= 256) { \ +- PyErr_SetString(PyExc_ValueError, \ +- "bytes must be in range(0, 256)"); \ +- goto error; \ +- } \ +- *str++ = (char) value; \ +- } \ +- return bytes; \ +- \ +- error: \ +- Py_DECREF(bytes); \ +- return NULL; \ +- } while (0) +- +-static PyObject* +-_PyBytes_FromList(PyObject *x) +-{ +- _PyBytes_FROM_LIST_BODY(x, PyList_GET_ITEM); +-} +- +-static PyObject* +-_PyBytes_FromTuple(PyObject *x) +-{ +- _PyBytes_FROM_LIST_BODY(x, PyTuple_GET_ITEM); +-} +- +-static PyObject * +-_PyBytes_FromIterator(PyObject *it, PyObject *x) +-{ +- char *str; +- Py_ssize_t i, size; +- _PyBytesWriter writer; +- +- /* For iterator version, create a string object and resize as needed */ +- size = PyObject_LengthHint(x, 64); +- if (size == -1 && PyErr_Occurred()) +- return NULL; +- +- _PyBytesWriter_Init(&writer); +- str = _PyBytesWriter_Alloc(&writer, size); +- if (str == NULL) +- return NULL; +- writer.overallocate = 1; +- size = writer.allocated; +- +- /* Run the iterator to exhaustion */ +- for (i = 0; ; i++) { +- PyObject *item; +- Py_ssize_t value; +- +- /* Get the next item */ +- item = PyIter_Next(it); +- if (item == NULL) { +- if (PyErr_Occurred()) +- goto error; +- break; +- } +- +- /* Interpret it as an int (__index__) */ +- value = PyNumber_AsSsize_t(item, NULL); +- Py_DECREF(item); +- if (value == -1 && PyErr_Occurred()) +- goto error; +- +- /* Range check */ +- if (value < 0 || value >= 256) { +- PyErr_SetString(PyExc_ValueError, +- "bytes must be in range(0, 256)"); +- goto error; +- } +- +- /* Append the byte */ +- if (i >= size) { +- str = _PyBytesWriter_Resize(&writer, str, size+1); +- if (str == NULL) +- return NULL; +- size = writer.allocated; +- } +- *str++ = (char) value; +- } +- +- return _PyBytesWriter_Finish(&writer, str); +- +- error: +- _PyBytesWriter_Dealloc(&writer); +- return NULL; +-} +- +-PyObject * +-PyBytes_FromObject(PyObject *x) +-{ +- PyObject *it, *result; +- +- if (x == NULL) { +- PyErr_BadInternalCall(); +- return NULL; +- } +- +- if (PyBytes_CheckExact(x)) { +- Py_INCREF(x); +- return x; +- } +- +- /* Use the modern buffer interface */ +- if (PyObject_CheckBuffer(x)) +- return _PyBytes_FromBuffer(x); +- +- if (PyList_CheckExact(x)) +- return _PyBytes_FromList(x); +- +- if (PyTuple_CheckExact(x)) +- return _PyBytes_FromTuple(x); +- +- if (!PyUnicode_Check(x)) { +- it = PyObject_GetIter(x); +- if (it != NULL) { +- result = _PyBytes_FromIterator(it, x); +- Py_DECREF(it); +- return result; +- } +- } +- +- PyErr_Format(PyExc_TypeError, +- "cannot convert '%.200s' object to bytes", +- x->ob_type->tp_name); +- return NULL; +-} +- +-static PyObject * +-bytes_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +-{ +- PyObject *tmp, *pnew; +- Py_ssize_t n; +- +- assert(PyType_IsSubtype(type, &PyBytes_Type)); +- tmp = bytes_new(&PyBytes_Type, args, kwds); +- if (tmp == NULL) +- return NULL; +- assert(PyBytes_Check(tmp)); +- n = PyBytes_GET_SIZE(tmp); +- pnew = type->tp_alloc(type, n); +- if (pnew != NULL) { +- memcpy(PyBytes_AS_STRING(pnew), +- PyBytes_AS_STRING(tmp), n+1); +- ((PyBytesObject *)pnew)->ob_shash = +- ((PyBytesObject *)tmp)->ob_shash; +- } +- Py_DECREF(tmp); +- return pnew; +-} +- +-PyDoc_STRVAR(bytes_doc, +-"bytes(iterable_of_ints) -> bytes\n\ +-bytes(string, encoding[, errors]) -> bytes\n\ +-bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n\ +-bytes(int) -> bytes object of size given by the parameter initialized with null bytes\n\ +-bytes() -> empty bytes object\n\ +-\n\ +-Construct an immutable array of bytes from:\n\ +- - an iterable yielding integers in range(256)\n\ +- - a text string encoded using the specified encoding\n\ +- - any object implementing the buffer API.\n\ +- - an integer"); +- +-static PyObject *bytes_iter(PyObject *seq); +- +-PyTypeObject PyBytes_Type = { +- PyVarObject_HEAD_INIT(&PyType_Type, 0) +- "bytes", +- PyBytesObject_SIZE, +- sizeof(char), +- bytes_dealloc, /* tp_dealloc */ +- 0, /* tp_print */ +- 0, /* tp_getattr */ +- 0, /* tp_setattr */ +- 0, /* tp_reserved */ +- (reprfunc)bytes_repr, /* tp_repr */ +- &bytes_as_number, /* tp_as_number */ +- &bytes_as_sequence, /* tp_as_sequence */ +- &bytes_as_mapping, /* tp_as_mapping */ +- (hashfunc)bytes_hash, /* tp_hash */ +- 0, /* tp_call */ +- bytes_str, /* tp_str */ +- PyObject_GenericGetAttr, /* tp_getattro */ +- 0, /* tp_setattro */ +- &bytes_as_buffer, /* tp_as_buffer */ +- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | +- Py_TPFLAGS_BYTES_SUBCLASS, /* tp_flags */ +- bytes_doc, /* tp_doc */ +- 0, /* tp_traverse */ +- 0, /* tp_clear */ +- (richcmpfunc)bytes_richcompare, /* tp_richcompare */ +- 0, /* tp_weaklistoffset */ +- bytes_iter, /* tp_iter */ +- 0, /* tp_iternext */ +- bytes_methods, /* tp_methods */ +- 0, /* tp_members */ +- 0, /* tp_getset */ +- &PyBaseObject_Type, /* tp_base */ +- 0, /* tp_dict */ +- 0, /* tp_descr_get */ +- 0, /* tp_descr_set */ +- 0, /* tp_dictoffset */ +- 0, /* tp_init */ +- 0, /* tp_alloc */ +- bytes_new, /* tp_new */ +- PyObject_Del, /* tp_free */ +-}; +- +-void +-PyBytes_Concat(PyObject **pv, PyObject *w) +-{ +- assert(pv != NULL); +- if (*pv == NULL) +- return; +- if (w == NULL) { +- Py_CLEAR(*pv); +- return; +- } +- +- if (Py_REFCNT(*pv) == 1 && PyBytes_CheckExact(*pv)) { +- /* Only one reference, so we can resize in place */ +- Py_ssize_t oldsize; +- Py_buffer wb; +- +- wb.len = -1; +- if (PyObject_GetBuffer(w, &wb, PyBUF_SIMPLE) != 0) { +- PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", +- Py_TYPE(w)->tp_name, Py_TYPE(*pv)->tp_name); +- Py_CLEAR(*pv); +- return; +- } +- +- oldsize = PyBytes_GET_SIZE(*pv); +- if (oldsize > PY_SSIZE_T_MAX - wb.len) { +- PyErr_NoMemory(); +- goto error; +- } +- if (_PyBytes_Resize(pv, oldsize + wb.len) < 0) +- goto error; +- +- memcpy(PyBytes_AS_STRING(*pv) + oldsize, wb.buf, wb.len); +- PyBuffer_Release(&wb); +- return; +- +- error: +- PyBuffer_Release(&wb); +- Py_CLEAR(*pv); +- return; +- } +- +- else { +- /* Multiple references, need to create new object */ +- PyObject *v; +- v = bytes_concat(*pv, w); +- Py_SETREF(*pv, v); +- } +-} +- +-void +-PyBytes_ConcatAndDel(PyObject **pv, PyObject *w) +-{ +- PyBytes_Concat(pv, w); +- Py_XDECREF(w); +-} +- +- +-/* The following function breaks the notion that bytes are immutable: +- it changes the size of a bytes object. We get away with this only if there +- is only one module referencing the object. You can also think of it +- as creating a new bytes object and destroying the old one, only +- more efficiently. In any case, don't use this if the bytes object may +- already be known to some other part of the code... +- Note that if there's not enough memory to resize the bytes object, the +- original bytes object at *pv is deallocated, *pv is set to NULL, an "out of +- memory" exception is set, and -1 is returned. Else (on success) 0 is +- returned, and the value in *pv may or may not be the same as on input. +- As always, an extra byte is allocated for a trailing \0 byte (newsize +- does *not* include that), and a trailing \0 byte is stored. +-*/ +- +-int +-_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize) +-{ +- PyObject *v; +- PyBytesObject *sv; +- v = *pv; +- if (!PyBytes_Check(v) || newsize < 0) { +- goto error; +- } +- if (Py_SIZE(v) == newsize) { +- /* return early if newsize equals to v->ob_size */ +- return 0; +- } +- if (Py_REFCNT(v) != 1) { +- goto error; +- } +- /* XXX UNREF/NEWREF interface should be more symmetrical */ +- _Py_DEC_REFTOTAL; +- _Py_ForgetReference(v); +- *pv = (PyObject *) +- PyObject_REALLOC(v, PyBytesObject_SIZE + newsize); +- if (*pv == NULL) { +- PyObject_Del(v); +- PyErr_NoMemory(); +- return -1; +- } +- _Py_NewReference(*pv); +- sv = (PyBytesObject *) *pv; +- Py_SIZE(sv) = newsize; +- sv->ob_sval[newsize] = '\0'; +- sv->ob_shash = -1; /* invalidate cached hash value */ +- return 0; +-error: +- *pv = 0; +- Py_DECREF(v); +- PyErr_BadInternalCall(); +- return -1; +-} +- +-void +-PyBytes_Fini(void) +-{ +- int i; +- for (i = 0; i < UCHAR_MAX + 1; i++) +- Py_CLEAR(characters[i]); +- Py_CLEAR(nullstring); +-} +- +-/*********************** Bytes Iterator ****************************/ +- +-typedef struct { +- PyObject_HEAD +- Py_ssize_t it_index; +- PyBytesObject *it_seq; /* Set to NULL when iterator is exhausted */ +-} striterobject; +- +-static void +-striter_dealloc(striterobject *it) +-{ +- _PyObject_GC_UNTRACK(it); +- Py_XDECREF(it->it_seq); +- PyObject_GC_Del(it); +-} +- +-static int +-striter_traverse(striterobject *it, visitproc visit, void *arg) +-{ +- Py_VISIT(it->it_seq); +- return 0; +-} +- +-static PyObject * +-striter_next(striterobject *it) +-{ +- PyBytesObject *seq; +- PyObject *item; +- +- assert(it != NULL); +- seq = it->it_seq; +- if (seq == NULL) +- return NULL; +- assert(PyBytes_Check(seq)); +- +- if (it->it_index < PyBytes_GET_SIZE(seq)) { +- item = PyLong_FromLong( +- (unsigned char)seq->ob_sval[it->it_index]); +- if (item != NULL) +- ++it->it_index; +- return item; +- } +- +- it->it_seq = NULL; +- Py_DECREF(seq); +- return NULL; +-} +- +-static PyObject * +-striter_len(striterobject *it) +-{ +- Py_ssize_t len = 0; +- if (it->it_seq) +- len = PyBytes_GET_SIZE(it->it_seq) - it->it_index; +- return PyLong_FromSsize_t(len); +-} +- +-PyDoc_STRVAR(length_hint_doc, +- "Private method returning an estimate of len(list(it))."); +- +-static PyObject * +-striter_reduce(striterobject *it) +-{ +- if (it->it_seq != NULL) { +- return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"), +- it->it_seq, it->it_index); +- } else { +- return Py_BuildValue("N(())", _PyObject_GetBuiltin("iter")); +- } +-} +- +-PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); +- +-static PyObject * +-striter_setstate(striterobject *it, PyObject *state) +-{ +- Py_ssize_t index = PyLong_AsSsize_t(state); +- if (index == -1 && PyErr_Occurred()) +- return NULL; +- if (it->it_seq != NULL) { +- if (index < 0) +- index = 0; +- else if (index > PyBytes_GET_SIZE(it->it_seq)) +- index = PyBytes_GET_SIZE(it->it_seq); /* iterator exhausted */ +- it->it_index = index; +- } +- Py_RETURN_NONE; +-} +- +-PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); +- +-static PyMethodDef striter_methods[] = { +- {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, +- length_hint_doc}, +- {"__reduce__", (PyCFunction)striter_reduce, METH_NOARGS, +- reduce_doc}, +- {"__setstate__", (PyCFunction)striter_setstate, METH_O, +- setstate_doc}, +- {NULL, NULL} /* sentinel */ +-}; +- +-PyTypeObject PyBytesIter_Type = { +- PyVarObject_HEAD_INIT(&PyType_Type, 0) +- "bytes_iterator", /* tp_name */ +- sizeof(striterobject), /* tp_basicsize */ +- 0, /* tp_itemsize */ +- /* methods */ +- (destructor)striter_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 */ +- PyObject_GenericGetAttr, /* tp_getattro */ +- 0, /* tp_setattro */ +- 0, /* tp_as_buffer */ +- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ +- 0, /* tp_doc */ +- (traverseproc)striter_traverse, /* tp_traverse */ +- 0, /* tp_clear */ +- 0, /* tp_richcompare */ +- 0, /* tp_weaklistoffset */ +- PyObject_SelfIter, /* tp_iter */ +- (iternextfunc)striter_next, /* tp_iternext */ +- striter_methods, /* tp_methods */ +- 0, +-}; +- +-static PyObject * +-bytes_iter(PyObject *seq) +-{ +- striterobject *it; +- +- if (!PyBytes_Check(seq)) { +- PyErr_BadInternalCall(); +- return NULL; +- } +- it = PyObject_GC_New(striterobject, &PyBytesIter_Type); +- if (it == NULL) +- return NULL; +- it->it_index = 0; +- Py_INCREF(seq); +- it->it_seq = (PyBytesObject *)seq; +- _PyObject_GC_TRACK(it); +- return (PyObject *)it; +-} +- +- +-/* _PyBytesWriter API */ +- +-#ifdef MS_WINDOWS +- /* On Windows, overallocate by 50% is the best factor */ +-# define OVERALLOCATE_FACTOR 2 +-#else +- /* On Linux, overallocate by 25% is the best factor */ +-# define OVERALLOCATE_FACTOR 4 +-#endif +- +-void +-_PyBytesWriter_Init(_PyBytesWriter *writer) +-{ +- /* Set all attributes before small_buffer to 0 */ +- memset(writer, 0, offsetof(_PyBytesWriter, small_buffer)); +-#ifdef Py_DEBUG +- memset(writer->small_buffer, 0xCB, sizeof(writer->small_buffer)); +-#endif +-} +- +-void +-_PyBytesWriter_Dealloc(_PyBytesWriter *writer) +-{ +- Py_CLEAR(writer->buffer); +-} +- +-Py_LOCAL_INLINE(char*) +-_PyBytesWriter_AsString(_PyBytesWriter *writer) +-{ +- if (writer->use_small_buffer) { +- assert(writer->buffer == NULL); +- return writer->small_buffer; +- } +- else if (writer->use_bytearray) { +- assert(writer->buffer != NULL); +- return PyByteArray_AS_STRING(writer->buffer); +- } +- else { +- assert(writer->buffer != NULL); +- return PyBytes_AS_STRING(writer->buffer); +- } +-} +- +-Py_LOCAL_INLINE(Py_ssize_t) +-_PyBytesWriter_GetSize(_PyBytesWriter *writer, char *str) +-{ +- char *start = _PyBytesWriter_AsString(writer); +- assert(str != NULL); +- assert(str >= start); +- assert(str - start <= writer->allocated); +- return str - start; +-} +- +-Py_LOCAL_INLINE(void) +-_PyBytesWriter_CheckConsistency(_PyBytesWriter *writer, char *str) +-{ +-#ifdef Py_DEBUG +- char *start, *end; +- +- if (writer->use_small_buffer) { +- assert(writer->buffer == NULL); +- } +- else { +- assert(writer->buffer != NULL); +- if (writer->use_bytearray) +- assert(PyByteArray_CheckExact(writer->buffer)); +- else +- assert(PyBytes_CheckExact(writer->buffer)); +- assert(Py_REFCNT(writer->buffer) == 1); +- } +- +- if (writer->use_bytearray) { +- /* bytearray has its own overallocation algorithm, +- writer overallocation must be disabled */ +- assert(!writer->overallocate); +- } +- +- assert(0 <= writer->allocated); +- assert(0 <= writer->min_size && writer->min_size <= writer->allocated); +- /* the last byte must always be null */ +- start = _PyBytesWriter_AsString(writer); +- assert(start[writer->allocated] == 0); +- +- end = start + writer->allocated; +- assert(str != NULL); +- assert(start <= str && str <= end); +-#endif +-} +- +-void* +-_PyBytesWriter_Resize(_PyBytesWriter *writer, void *str, Py_ssize_t size) +-{ +- Py_ssize_t allocated, pos; +- +- _PyBytesWriter_CheckConsistency(writer, str); +- assert(writer->allocated < size); +- +- allocated = size; +- if (writer->overallocate +- && allocated <= (PY_SSIZE_T_MAX - allocated / OVERALLOCATE_FACTOR)) { +- /* overallocate to limit the number of realloc() */ +- allocated += allocated / OVERALLOCATE_FACTOR; +- } +- +- pos = _PyBytesWriter_GetSize(writer, str); +- if (!writer->use_small_buffer) { +- if (writer->use_bytearray) { +- if (PyByteArray_Resize(writer->buffer, allocated)) +- goto error; +- /* writer->allocated can be smaller than writer->buffer->ob_alloc, +- but we cannot use ob_alloc because bytes may need to be moved +- to use the whole buffer. bytearray uses an internal optimization +- to avoid moving or copying bytes when bytes are removed at the +- beginning (ex: del bytearray[:1]). */ +- } +- else { +- if (_PyBytes_Resize(&writer->buffer, allocated)) +- goto error; +- } +- } +- else { +- /* convert from stack buffer to bytes object buffer */ +- assert(writer->buffer == NULL); +- +- if (writer->use_bytearray) +- writer->buffer = PyByteArray_FromStringAndSize(NULL, allocated); +- else +- writer->buffer = PyBytes_FromStringAndSize(NULL, allocated); +- if (writer->buffer == NULL) +- goto error; +- +- if (pos != 0) { +- char *dest; +- if (writer->use_bytearray) +- dest = PyByteArray_AS_STRING(writer->buffer); +- else +- dest = PyBytes_AS_STRING(writer->buffer); +- memcpy(dest, +- writer->small_buffer, +- pos); +- } +- +- writer->use_small_buffer = 0; +-#ifdef Py_DEBUG +- memset(writer->small_buffer, 0xDB, sizeof(writer->small_buffer)); +-#endif +- } +- writer->allocated = allocated; +- +- str = _PyBytesWriter_AsString(writer) + pos; +- _PyBytesWriter_CheckConsistency(writer, str); +- return str; +- +-error: +- _PyBytesWriter_Dealloc(writer); +- return NULL; +-} +- +-void* +-_PyBytesWriter_Prepare(_PyBytesWriter *writer, void *str, Py_ssize_t size) +-{ +- Py_ssize_t new_min_size; +- +- _PyBytesWriter_CheckConsistency(writer, str); +- assert(size >= 0); +- +- if (size == 0) { +- /* nothing to do */ +- return str; +- } +- +- if (writer->min_size > PY_SSIZE_T_MAX - size) { +- PyErr_NoMemory(); +- _PyBytesWriter_Dealloc(writer); +- return NULL; +- } +- new_min_size = writer->min_size + size; +- +- if (new_min_size > writer->allocated) +- str = _PyBytesWriter_Resize(writer, str, new_min_size); +- +- writer->min_size = new_min_size; +- return str; +-} +- +-/* Allocate the buffer to write size bytes. +- Return the pointer to the beginning of buffer data. +- Raise an exception and return NULL on error. */ +-void* +-_PyBytesWriter_Alloc(_PyBytesWriter *writer, Py_ssize_t size) +-{ +- /* ensure that _PyBytesWriter_Alloc() is only called once */ +- assert(writer->min_size == 0 && writer->buffer == NULL); +- assert(size >= 0); +- +- writer->use_small_buffer = 1; +-#ifdef Py_DEBUG +- writer->allocated = sizeof(writer->small_buffer) - 1; +- /* In debug mode, don't use the full small buffer because it is less +- efficient than bytes and bytearray objects to detect buffer underflow +- and buffer overflow. Use 10 bytes of the small buffer to test also +- code using the smaller buffer in debug mode. +- +- Don't modify the _PyBytesWriter structure (use a shorter small buffer) +- in debug mode to also be able to detect stack overflow when running +- tests in debug mode. The _PyBytesWriter is large (more than 512 bytes), +- if Py_EnterRecursiveCall() is not used in deep C callback, we may hit a +- stack overflow. */ +- writer->allocated = Py_MIN(writer->allocated, 10); +- /* _PyBytesWriter_CheckConsistency() requires the last byte to be 0, +- to detect buffer overflow */ +- writer->small_buffer[writer->allocated] = 0; +-#else +- writer->allocated = sizeof(writer->small_buffer); +-#endif +- return _PyBytesWriter_Prepare(writer, writer->small_buffer, size); +-} +- +-PyObject * +-_PyBytesWriter_Finish(_PyBytesWriter *writer, void *str) +-{ +- Py_ssize_t size; +- PyObject *result; +- +- _PyBytesWriter_CheckConsistency(writer, str); +- +- size = _PyBytesWriter_GetSize(writer, str); +- if (size == 0 && !writer->use_bytearray) { +- Py_CLEAR(writer->buffer); +- /* Get the empty byte string singleton */ +- result = PyBytes_FromStringAndSize(NULL, 0); +- } +- else if (writer->use_small_buffer) { +- if (writer->use_bytearray) { +- result = PyByteArray_FromStringAndSize(writer->small_buffer, size); +- } +- else { +- result = PyBytes_FromStringAndSize(writer->small_buffer, size); +- } +- } +- else { +- result = writer->buffer; +- writer->buffer = NULL; +- +- if (size != writer->allocated) { +- if (writer->use_bytearray) { +- if (PyByteArray_Resize(result, size)) { +- Py_DECREF(result); +- return NULL; +- } +- } +- else { +- if (_PyBytes_Resize(&result, size)) { +- assert(result == NULL); +- return NULL; +- } +- } +- } +- } +- return result; +-} +- +-void* +-_PyBytesWriter_WriteBytes(_PyBytesWriter *writer, void *ptr, +- const void *bytes, Py_ssize_t size) +-{ +- char *str = (char *)ptr; +- +- str = _PyBytesWriter_Prepare(writer, str, size); +- if (str == NULL) +- return NULL; +- +- memcpy(str, bytes, size); +- str += size; +- +- return str; +-} +diff --git a/Objects/classobject.c b/Objects/classobject.c +index 5b645787cb..02d7cfd019 100644 +--- a/Objects/classobject.c ++++ b/Objects/classobject.c +@@ -1009,7 +1009,7 @@ instance_hash(PyInstanceObject *inst) + Py_DECREF(func); + if (res == NULL) + return -1; +- if (PyInt_Check(res) || PyLong_Check(res)) ++ if (_PyAnyInt_Check(res)) + /* This already converts a -1 result to -2. */ + outcome = Py_TYPE(res)->tp_hash(res); + else { +diff --git a/Objects/codeobject.c b/Objects/codeobject.c +index a66aa6905a..d50e4c61f0 100644 +--- a/Objects/codeobject.c ++++ b/Objects/codeobject.c +@@ -423,10 +423,9 @@ _PyCode_ConstantKey(PyObject *op) + + /* Py_None is a singleton */ + if (op == Py_None +- || PyInt_CheckExact(op) +- || PyLong_CheckExact(op) +- || PyBool_Check(op) +- || PyBytes_CheckExact(op) ++ || _PyAnyInt_CheckExact(op) ++ || PyBool_Check(op) ++ || PyBytes_CheckExact(op) + #ifdef Py_USING_UNICODE + || PyUnicode_CheckExact(op) + #endif +diff --git a/Objects/complexobject.c b/Objects/complexobject.c +index aaefa2dcda..871eea319f 100644 +--- a/Objects/complexobject.c ++++ b/Objects/complexobject.c +@@ -796,7 +796,7 @@ complex_richcompare(PyObject *v, PyObject *w, int op) + * NotImplemented. Only comparisons with core numeric types raise + * TypeError. + */ +- if (PyInt_Check(w) || PyLong_Check(w) || ++ if (_PyAnyInt_Check(w) || + PyFloat_Check(w) || PyComplex_Check(w)) { + PyErr_SetString(PyExc_TypeError, + "no ordering relation is defined " +@@ -809,7 +809,7 @@ complex_richcompare(PyObject *v, PyObject *w, int op) + assert(PyComplex_Check(v)); + TO_COMPLEX(v, i); + +- if (PyInt_Check(w) || PyLong_Check(w)) { ++ if (_PyAnyInt_Check(w)) { + /* Check for 0.0 imaginary part first to avoid the rich + * comparison when possible. + */ +diff --git a/Objects/enumobject.c b/Objects/enumobject.c +index 8f86a5b8de..73b656b8e0 100644 +--- a/Objects/enumobject.c ++++ b/Objects/enumobject.c +@@ -31,7 +31,7 @@ enum_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + Py_DECREF(en); + return NULL; + } +- assert(PyInt_Check(start) || PyLong_Check(start)); ++ assert(_PyAnyInt_Check(start)); + en->en_index = PyInt_AsSsize_t(start); + if (en->en_index == -1 && PyErr_Occurred()) { + PyErr_Clear(); +diff --git a/Objects/floatobject.c b/Objects/floatobject.c +index 37dd67e669..5954d39cdb 100644 +--- a/Objects/floatobject.c ++++ b/Objects/floatobject.c +@@ -428,7 +428,7 @@ float_richcompare(PyObject *v, PyObject *w, int op) + j = PyFloat_AS_DOUBLE(w); + + else if (!Py_IS_FINITE(i)) { +- if (PyInt_Check(w) || PyLong_Check(w)) ++ if (_PyAnyInt_Check(w)) + /* If i is an infinity, its magnitude exceeds any + * finite integer, so it doesn't matter which int we + * compare i with. If i is a NaN, similarly. +diff --git a/Objects/intobject.c b/Objects/intobject.c +index 3ab00af1e2..9b27c35d88 100644 +--- a/Objects/intobject.c ++++ b/Objects/intobject.c +@@ -358,7 +358,7 @@ PyInt_FromString(char *s, char **pend, int base) + + if ((base != 0 && base < 2) || base > 36) { + PyErr_SetString(PyExc_ValueError, +- "int() base must be >= 2 and <= 36"); ++ "int() base must be >= 2 and <= 36, or 0"); + return NULL; + } + +diff --git a/Objects/longobject.c b/Objects/longobject.c +index 5d6ce70d53..f40ad7ab1b 100644 +--- a/Objects/longobject.c ++++ b/Objects/longobject.c +@@ -1722,7 +1722,7 @@ PyLong_FromString(char *str, char **pend, int base) + + if ((base != 0 && base < 2) || base > 36) { + PyErr_SetString(PyExc_ValueError, +- "long() arg 2 must be >= 2 and <= 36"); ++ "long() base must be >= 2 and <= 36, or 0"); + return NULL; + } + while (*str != '\0' && isspace(Py_CHARMASK(*str))) +diff --git a/Objects/moduleobject.c b/Objects/moduleobject.c +index f2fed30e90..fd48ff176e 100644 +--- a/Objects/moduleobject.c ++++ b/Objects/moduleobject.c +@@ -221,7 +221,7 @@ The name must be a string; the optional doc argument can have any type."); + PyTypeObject PyModule_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "module", /* tp_name */ +- sizeof(PyModuleObject), /* tp_size */ ++ sizeof(PyModuleObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)module_dealloc, /* tp_dealloc */ + 0, /* tp_print */ +diff --git a/Objects/setobject.c b/Objects/setobject.c +index 154be43564..31da3dbfec 100644 +--- a/Objects/setobject.c ++++ b/Objects/setobject.c +@@ -1710,8 +1710,10 @@ set_symmetric_difference(PySetObject *so, PyObject *other) + if (otherset == NULL) + return NULL; + rv = set_symmetric_difference_update(otherset, (PyObject *)so); +- if (rv == NULL) ++ if (rv == NULL) { ++ Py_DECREF(otherset); + return NULL; ++ } + Py_DECREF(rv); + return (PyObject *)otherset; + } +diff --git a/Objects/sliceobject.c b/Objects/sliceobject.c +index c66e057cdb..dc18211573 100644 +--- a/Objects/sliceobject.c ++++ b/Objects/sliceobject.c +@@ -107,20 +107,20 @@ PySlice_GetIndices(PySliceObject *r, Py_ssize_t length, + if (r->step == Py_None) { + *step = 1; + } else { +- if (!PyInt_Check(r->step) && !PyLong_Check(r->step)) return -1; ++ if (!_PyAnyInt_Check(r->step)) return -1; + *step = PyInt_AsSsize_t(r->step); + } + if (r->start == Py_None) { + *start = *step < 0 ? length-1 : 0; + } else { +- if (!PyInt_Check(r->start) && !PyLong_Check(r->step)) return -1; ++ if (!_PyAnyInt_Check(r->start)) return -1; + *start = PyInt_AsSsize_t(r->start); + if (*start < 0) *start += length; + } + if (r->stop == Py_None) { + *stop = *step < 0 ? -1 : length; + } else { +- if (!PyInt_Check(r->stop) && !PyLong_Check(r->step)) return -1; ++ if (!_PyAnyInt_Check(r->stop)) return -1; + *stop = PyInt_AsSsize_t(r->stop); + if (*stop < 0) *stop += length; + } +diff --git a/Objects/stringobject.c b/Objects/stringobject.c +index 59d22e7694..b21afb4424 100644 +--- a/Objects/stringobject.c ++++ b/Objects/stringobject.c +@@ -4504,7 +4504,7 @@ PyString_Format(PyObject *format, PyObject *args) + if (PyNumber_Check(v)) { + PyObject *iobj=NULL; + +- if (PyInt_Check(v) || (PyLong_Check(v))) { ++ if (_PyAnyInt_Check(v)) { + iobj = v; + Py_INCREF(iobj); + } +diff --git a/Objects/typeobject.c b/Objects/typeobject.c +index 685c545773..844fb00749 100644 +--- a/Objects/typeobject.c ++++ b/Objects/typeobject.c +@@ -2082,6 +2082,9 @@ type_init(PyObject *cls, PyObject *args, PyObject *kwds) + /* Call object.__init__(self) now. */ + /* XXX Could call super(type, cls).__init__() but what's the point? */ + args = PyTuple_GetSlice(args, 0, 0); ++ if (args == NULL) { ++ return -1; ++ } + res = object_init(cls, args, NULL); + Py_DECREF(args); + return res; +@@ -2608,6 +2611,7 @@ type_getattro(PyTypeObject *type, PyObject *name) + PyTypeObject *metatype = Py_TYPE(type); + PyObject *meta_attribute, *attribute; + descrgetfunc meta_get; ++ PyObject* res; + + if (!PyString_Check(name)) { + PyErr_Format(PyExc_TypeError, +@@ -2629,6 +2633,7 @@ type_getattro(PyTypeObject *type, PyObject *name) + meta_attribute = _PyType_Lookup(metatype, name); + + if (meta_attribute != NULL) { ++ Py_INCREF(meta_attribute); + meta_get = Py_TYPE(meta_attribute)->tp_descr_get; + + if (meta_get != NULL && PyDescr_IsData(meta_attribute)) { +@@ -2636,10 +2641,11 @@ type_getattro(PyTypeObject *type, PyObject *name) + * writes. Assume the attribute is not overridden in + * type's tp_dict (and bases): call the descriptor now. + */ +- return meta_get(meta_attribute, (PyObject *)type, +- (PyObject *)metatype); ++ res = meta_get(meta_attribute, (PyObject *)type, ++ (PyObject *)metatype); ++ Py_DECREF(meta_attribute); ++ return res; + } +- Py_INCREF(meta_attribute); + } + + /* No data descriptor found on metatype. Look in tp_dict of this +@@ -2647,18 +2653,21 @@ type_getattro(PyTypeObject *type, PyObject *name) + attribute = _PyType_Lookup(type, name); + if (attribute != NULL) { + /* Implement descriptor functionality, if any */ +- descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get; ++ descrgetfunc local_get; ++ Py_INCREF(attribute); ++ local_get = Py_TYPE(attribute)->tp_descr_get; + + Py_XDECREF(meta_attribute); + + if (local_get != NULL) { + /* NULL 2nd argument indicates the descriptor was + * found on the target object itself (or a base) */ +- return local_get(attribute, (PyObject *)NULL, +- (PyObject *)type); ++ res = local_get(attribute, (PyObject *)NULL, ++ (PyObject *)type); ++ Py_DECREF(attribute); ++ return res; + } + +- Py_INCREF(attribute); + return attribute; + } + +diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c +index d011f7d50c..b76db619ad 100644 +--- a/Objects/unicodeobject.c ++++ b/Objects/unicodeobject.c +@@ -4222,7 +4222,7 @@ PyObject *PyUnicode_DecodeCharmap(const char *s, + p = PyUnicode_AS_UNICODE(v) + oldpos; + } + value -= 0x10000; +- *p++ = 0xD800 | (value >> 10); ++ *p++ = 0xD800 | (Py_UNICODE)(value >> 10); + *p++ = 0xDC00 | (value & 0x3FF); + extrachars -= 2; + } +@@ -8628,7 +8628,7 @@ PyObject *PyUnicode_Format(PyObject *format, + if (PyNumber_Check(v)) { + PyObject *iobj=NULL; + +- if (PyInt_Check(v) || (PyLong_Check(v))) { ++ if (_PyAnyInt_Check(v)) { + iobj = v; + Py_INCREF(iobj); + } +diff --git a/PC/_msi.c b/PC/_msi.c +index d7700f09c7..68c4e79e29 100644 +--- a/PC/_msi.c ++++ b/PC/_msi.c +@@ -321,6 +321,10 @@ msierror(int status) + code = MsiRecordGetInteger(err, 1); /* XXX code */ + if (MsiFormatRecord(0, err, res, &size) == ERROR_MORE_DATA) { + res = malloc(size+1); ++ if (res == NULL) { ++ MsiCloseHandle(err); ++ return PyErr_NoMemory(); ++ } + MsiFormatRecord(0, err, res, &size); + res[size]='\0'; + } +@@ -544,6 +548,9 @@ summary_getproperty(msiobj* si, PyObject *args) + &fval, sval, &ssize); + if (status == ERROR_MORE_DATA) { + sval = malloc(ssize); ++ if (sval == NULL) { ++ return PyErr_NoMemory(); ++ } + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); + } +diff --git a/PC/_subprocess.c b/PC/_subprocess.c +index fc9aaa4611..66940ff7e4 100644 +--- a/PC/_subprocess.c ++++ b/PC/_subprocess.c +@@ -381,7 +381,7 @@ getenvironment(PyObject* environment) + } + totalsize = (p - PyString_AS_STRING(out)) + ksize + 1 + + vsize + 1 + 1; +- if (totalsize > PyString_GET_SIZE(out)) { ++ if (totalsize > (size_t)PyString_GET_SIZE(out)) { + size_t offset = p - PyString_AS_STRING(out); + if (_PyString_Resize(&out, totalsize + 1024)) + goto exit; +diff --git a/PC/_winreg.c b/PC/_winreg.c +index e139cce85f..f0f8df3310 100644 +--- a/PC/_winreg.c ++++ b/PC/_winreg.c +@@ -641,7 +641,7 @@ PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK) + PyHKEYObject *pH = (PyHKEYObject *)ob; + *pHANDLE = pH->hkey; + } +- else if (PyInt_Check(ob) || PyLong_Check(ob)) { ++ else if (_PyAnyInt_Check(ob)) { + /* We also support integers */ + PyErr_Clear(); + *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); +@@ -753,8 +753,7 @@ Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize) + Py_ssize_t i,j; + switch (typ) { + case REG_DWORD: +- if (value != Py_None && +- !(PyInt_Check(value) || PyLong_Check(value))) ++ if (value != Py_None && !_PyAnyInt_Check(value)) + return FALSE; + *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); + if (*retDataBuf==NULL){ +diff --git a/Parser/asdl_c.py b/Parser/asdl_c.py +index 08353a9e7f..ac61c78afc 100755 +--- a/Parser/asdl_c.py ++++ b/Parser/asdl_c.py +@@ -830,7 +830,7 @@ static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena) + static int obj2ast_int(PyObject* obj, int* out, PyArena* arena) + { + int i; +- if (!PyInt_Check(obj) && !PyLong_Check(obj)) { ++ if (!_PyAnyInt_Check(obj)) { + PyObject *s = PyObject_Repr(obj); + if (s == NULL) return 1; + PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s", +diff --git a/Parser/grammar.c b/Parser/grammar.c +index fa1dd7cdf8..fcd2219110 100644 +--- a/Parser/grammar.c ++++ b/Parser/grammar.c +@@ -32,6 +32,24 @@ newgrammar(int start) + return g; + } + ++void ++freegrammar(grammar *g) ++{ ++ int i; ++ for (i = 0; i < g->g_ndfas; i++) { ++ int j; ++ free(g->g_dfa[i].d_name); ++ for (j = 0; j < g->g_dfa[i].d_nstates; j++) ++ PyObject_FREE(g->g_dfa[i].d_state[j].s_arc); ++ PyObject_FREE(g->g_dfa[i].d_state); ++ } ++ PyObject_FREE(g->g_dfa); ++ for (i = 0; i < g->g_ll.ll_nlabels; i++) ++ free(g->g_ll.ll_label[i].lb_str); ++ PyObject_FREE(g->g_ll.ll_label); ++ PyObject_FREE(g); ++} ++ + dfa * + adddfa(grammar *g, int type, char *name) + { +diff --git a/Parser/parsetok.c b/Parser/parsetok.c +index 069cc6b711..a5e922243c 100644 +--- a/Parser/parsetok.c ++++ b/Parser/parsetok.c +@@ -176,7 +176,7 @@ parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, + } + else + started = 1; +- len = b - a; /* XXX this may compute NULL - NULL */ ++ len = (a != NULL && b != NULL) ? b - a : 0; + str = (char *) PyObject_MALLOC(len + 1); + if (str == NULL) { + fprintf(stderr, "no mem for next token\n"); +@@ -189,10 +189,12 @@ parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, + + #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD + #endif +- if (a >= tok->line_start) ++ if (a != NULL && a >= tok->line_start) { + col_offset = a - tok->line_start; +- else ++ } ++ else { + col_offset = -1; ++ } + + if ((err_ret->error = + PyParser_AddToken(ps, (int)type, str, tok->lineno, col_offset, +diff --git a/Parser/pgen.c b/Parser/pgen.c +index f3031aea0b..b20d9764a1 100644 +--- a/Parser/pgen.c ++++ b/Parser/pgen.c +@@ -117,6 +117,17 @@ newnfagrammar(void) + return gr; + } + ++static void ++freenfagrammar(nfagrammar *gr) ++{ ++ int i; ++ for (i = 0; i < gr->gr_nnfas; i++) { ++ PyObject_FREE(gr->gr_nfa[i]->nf_state); ++ } ++ PyObject_FREE(gr->gr_nfa); ++ PyObject_FREE(gr); ++} ++ + static nfa * + addnfa(nfagrammar *gr, char *name) + { +@@ -394,6 +405,7 @@ makedfa(nfagrammar *gr, nfa *nf, dfa *d) + int istate, jstate, iarc, jarc, ibit; + nfastate *st; + nfaarc *ar; ++ int i, j; + + ss = newbitset(nbits); + addclosure(ss, nf, nf->nf_start); +@@ -488,7 +500,11 @@ makedfa(nfagrammar *gr, nfa *nf, dfa *d) + + convert(d, xx_nstates, xx_state); + +- /* XXX cleanup */ ++ for (i = 0; i < xx_nstates; i++) { ++ for (j = 0; j < xx_state[i].ss_narcs; j++) ++ delbitset(xx_state[i].ss_arc[j].sa_bitset); ++ PyObject_FREE(xx_state[i].ss_arc); ++ } + PyObject_FREE(xx_state); + } + +@@ -669,7 +685,7 @@ pgen(node *n) + g = maketables(gr); + translatelabels(g); + addfirstsets(g); +- PyObject_FREE(gr); ++ freenfagrammar(gr); + return g; + } + +diff --git a/Parser/pgenmain.c b/Parser/pgenmain.c +index 88fa7f19b8..0b47295c1b 100644 +--- a/Parser/pgenmain.c ++++ b/Parser/pgenmain.c +@@ -67,6 +67,7 @@ main(int argc, char **argv) + printf("Writing %s ...\n", graminit_h); + printnonterminals(g, fp); + fclose(fp); ++ freegrammar(g); + Py_Exit(0); + return 0; /* Make gcc -Wall happy */ + } +diff --git a/Parser/tokenizer.c b/Parser/tokenizer.c +index 4fdbad9393..c6e61df533 100644 +--- a/Parser/tokenizer.c ++++ b/Parser/tokenizer.c +@@ -1636,6 +1636,8 @@ tok_get(register struct tok_state *tok, char **p_start, char **p_end) + "<> not supported in 3.x; use !=", + tok->filename, tok->lineno, + NULL, NULL)) { ++ tok->done = E_ERROR; ++ tok->cur = tok->inp; + return ERRORTOKEN; + } + } +@@ -1679,6 +1681,11 @@ int + PyTokenizer_Get(struct tok_state *tok, char **p_start, char **p_end) + { + int result = tok_get(tok, p_start, p_end); ++ if (tok->fp && ferror(tok->fp)) { ++ clearerr(tok->fp); ++ result = ERRORTOKEN; ++ tok->done = E_IO; ++ } + if (tok->decoding_erred) { + result = ERRORTOKEN; + tok->done = E_DECODE; +diff --git a/Python/Python-ast.c b/Python/Python-ast.c +index 4ac5cf578f..2e7a1afbbc 100644 +--- a/Python/Python-ast.c ++++ b/Python/Python-ast.c +@@ -617,7 +617,7 @@ static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena) + static int obj2ast_int(PyObject* obj, int* out, PyArena* arena) + { + int i; +- if (!PyInt_Check(obj) && !PyLong_Check(obj)) { ++ if (!_PyAnyInt_Check(obj)) { + PyObject *s = PyObject_Repr(obj); + if (s == NULL) return 1; + PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s", +diff --git a/Python/ast.c b/Python/ast.c +index 318c0bb27d..946032589f 100644 +--- a/Python/ast.c ++++ b/Python/ast.c +@@ -2520,6 +2520,8 @@ alias_for_import_name(struct compiling *c, const node *n, int store) + break; + case STAR: + str = PyString_InternFromString("*"); ++ if (!str) ++ return NULL; + PyArena_AddPyObject(c->c_arena, str); + return alias(str, NULL, c->c_arena); + default: +diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c +index 9ce3b275ea..4b819da8b3 100644 +--- a/Python/bltinmodule.c ++++ b/Python/bltinmodule.c +@@ -1780,7 +1780,7 @@ get_range_long_argument(PyObject *arg, const char *name) + { + PyObject *v; + PyNumberMethods *nb; +- if (PyInt_Check(arg) || PyLong_Check(arg)) { ++ if (_PyAnyInt_Check(arg)) { + Py_INCREF(arg); + return arg; + } +@@ -1795,7 +1795,7 @@ get_range_long_argument(PyObject *arg, const char *name) + v = nb->nb_int(arg); + if (v == NULL) + return NULL; +- if (PyInt_Check(v) || PyLong_Check(v)) ++ if (_PyAnyInt_Check(v)) + return v; + Py_DECREF(v); + PyErr_SetString(PyExc_TypeError, +@@ -2363,6 +2363,11 @@ builtin_sum(PyObject *self, PyObject *args) + } + /* Either overflowed or is not an int. Restore real objects and process normally */ + result = PyInt_FromLong(i_result); ++ if (result == NULL) { ++ Py_DECREF(item); ++ Py_DECREF(iter); ++ return NULL; ++ } + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); +@@ -2401,6 +2406,11 @@ builtin_sum(PyObject *self, PyObject *args) + continue; + } + result = PyFloat_FromDouble(f_result); ++ if (result == NULL) { ++ Py_DECREF(item); ++ Py_DECREF(iter); ++ return NULL; ++ } + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); +diff --git a/Python/ceval.c b/Python/ceval.c +index b55b4d6688..2088a271d8 100644 +--- a/Python/ceval.c ++++ b/Python/ceval.c +@@ -4750,8 +4750,7 @@ _PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi) + + + #undef ISINDEX +-#define ISINDEX(x) ((x) == NULL || \ +- PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x)) ++#define ISINDEX(x) ((x) == NULL || _PyAnyInt_Check(x) || PyIndex_Check(x)) + + static PyObject * + apply_slice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */ +diff --git a/Python/getargs.c b/Python/getargs.c +index 32ff6fc069..cc1ddde977 100644 +--- a/Python/getargs.c ++++ b/Python/getargs.c +@@ -1780,7 +1780,7 @@ skipitem(const char **p_format, va_list *p_va, int flags) + else + (void) va_arg(*p_va, int *); + format++; +- } else if ((c == 's' || c == 'z') && *format == '*') { ++ } else if ((c == 's' || c == 'z' || c == 'w') && *format == '*') { + format++; + } + break; +diff --git a/Python/import.c b/Python/import.c +index 1d74faf5f6..f43a47c1c4 100644 +--- a/Python/import.c ++++ b/Python/import.c +@@ -447,7 +447,9 @@ PyImport_Cleanup(void) + dict = PyModule_GetDict(value); + if (Py_VerboseFlag) + PySys_WriteStderr("# clear __builtin__._\n"); +- PyDict_SetItemString(dict, "_", Py_None); ++ if (PyDict_SetItemString(dict, "_", Py_None) < 0) { ++ PyErr_Clear(); ++ } + } + value = PyDict_GetItemString(modules, "sys"); + if (value != NULL && PyModule_Check(value)) { +@@ -457,7 +459,9 @@ PyImport_Cleanup(void) + for (p = sys_deletes; *p != NULL; p++) { + if (Py_VerboseFlag) + PySys_WriteStderr("# clear sys.%s\n", *p); +- PyDict_SetItemString(dict, *p, Py_None); ++ if (PyDict_SetItemString(dict, *p, Py_None) < 0) { ++ PyErr_Clear(); ++ } + } + for (p = sys_files; *p != NULL; p+=2) { + if (Py_VerboseFlag) +@@ -465,7 +469,9 @@ PyImport_Cleanup(void) + v = PyDict_GetItemString(dict, *(p+1)); + if (v == NULL) + v = Py_None; +- PyDict_SetItemString(dict, *p, v); ++ if (PyDict_SetItemString(dict, *p, v) < 0) { ++ PyErr_Clear(); ++ } + } + } + +@@ -475,7 +481,9 @@ PyImport_Cleanup(void) + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup __main__\n"); + _PyModule_Clear(value); +- PyDict_SetItemString(modules, "__main__", Py_None); ++ if (PyDict_SetItemString(modules, "__main__", Py_None) < 0) { ++ PyErr_Clear(); ++ } + } + + /* The special treatment of __builtin__ here is because even +@@ -510,10 +518,15 @@ PyImport_Cleanup(void) + PySys_WriteStderr( + "# cleanup[1] %s\n", name); + _PyModule_Clear(value); +- PyDict_SetItem(modules, key, Py_None); ++ if (PyDict_SetItem(modules, key, Py_None) < 0) { ++ PyErr_Clear(); ++ } + ndone++; + } + } ++ if (PyErr_Occurred()) { ++ PyErr_Clear(); ++ } + } while (ndone > 0); + + /* Next, delete all modules (still skipping __builtin__ and sys) */ +@@ -528,7 +541,12 @@ PyImport_Cleanup(void) + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup[2] %s\n", name); + _PyModule_Clear(value); +- PyDict_SetItem(modules, key, Py_None); ++ if (PyDict_SetItem(modules, key, Py_None) < 0) { ++ PyErr_Clear(); ++ } ++ } ++ if (PyErr_Occurred()) { ++ PyErr_Clear(); + } + } + +@@ -538,14 +556,18 @@ PyImport_Cleanup(void) + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup sys\n"); + _PyModule_Clear(value); +- PyDict_SetItemString(modules, "sys", Py_None); ++ if (PyDict_SetItemString(modules, "sys", Py_None) < 0) { ++ PyErr_Clear(); ++ } + } + 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); ++ if (PyDict_SetItemString(modules, "__builtin__", Py_None) < 0) { ++ PyErr_Clear(); ++ } + } + + /* Finally, clear and delete the modules directory */ +diff --git a/Python/pythonrun.c b/Python/pythonrun.c +index 44fe13d2f7..2c9f55fbd1 100644 +--- a/Python/pythonrun.c ++++ b/Python/pythonrun.c +@@ -1136,7 +1136,7 @@ handle_system_exit(void) + /* If we failed to dig out the 'code' attribute, + just let the else clause below print the error. */ + } +- if (PyInt_Check(value) || PyLong_Check(value)) ++ if (_PyAnyInt_Check(value)) + exitcode = (int)PyInt_AsLong(value); + else { + PyObject *sys_stderr = PySys_GetObject("stderr"); +@@ -1590,7 +1590,7 @@ err_input(perrdetail *err) + errtype = PyExc_SyntaxError; + switch (err->error) { + case E_ERROR: +- return; ++ goto cleanup; + case E_SYNTAX: + errtype = PyExc_IndentationError; + if (err->expected == INDENT) +@@ -1654,6 +1654,9 @@ err_input(perrdetail *err) + Py_XDECREF(tb); + break; + } ++ case E_IO: ++ msg = "I/O error while reading"; ++ break; + case E_LINECONT: + msg = "unexpected character after line continuation character"; + break; +diff --git a/Tools/gdb/libpython.py b/Tools/gdb/libpython.py +index e218a31f59..3ae70974cc 100755 +--- a/Tools/gdb/libpython.py ++++ b/Tools/gdb/libpython.py +@@ -241,12 +241,13 @@ class PyObjectPtr(object): + + def safe_tp_name(self): + try: +- return self.type().field('tp_name').string() +- except NullPyObjectPtr: +- # NULL tp_name? +- return 'unknown' +- except RuntimeError: +- # Can't even read the object at all? ++ ob_type = self.type() ++ tp_name = ob_type.field('tp_name') ++ return tp_name.string() ++ # NullPyObjectPtr: NULL tp_name? ++ # RuntimeError: Can't even read the object at all? ++ # UnicodeDecodeError: Failed to decode tp_name bytestring ++ except (NullPyObjectPtr, RuntimeError, UnicodeDecodeError): + return 'unknown' + + def proxyval(self, visited): +@@ -320,7 +321,9 @@ class PyObjectPtr(object): + try: + tp_name = t.field('tp_name').string() + tp_flags = int(t.field('tp_flags')) +- except RuntimeError: ++ # RuntimeError: NULL pointers ++ # UnicodeDecodeError: string() fails to decode the bytestring ++ except (RuntimeError, UnicodeDecodeError): + # Handle any kind of error e.g. NULL ptrs by simply using the base + # class + return cls +@@ -336,6 +339,7 @@ class PyObjectPtr(object): + 'set' : PySetObjectPtr, + 'frozenset' : PySetObjectPtr, + 'builtin_function_or_method' : PyCFunctionObjectPtr, ++ 'method-wrapper': wrapperobject, + } + if tp_name in name_map: + return name_map[tp_name] +@@ -602,7 +606,10 @@ class PyCFunctionObjectPtr(PyObjectPtr): + + def proxyval(self, visited): + m_ml = self.field('m_ml') # m_ml is a (PyMethodDef*) +- ml_name = m_ml['ml_name'].string() ++ try: ++ ml_name = m_ml['ml_name'].string() ++ except UnicodeDecodeError: ++ ml_name = '' + + pyop_m_self = self.pyop_field('m_self') + if pyop_m_self.is_null(): +@@ -1131,7 +1138,9 @@ class PyUnicodeObjectPtr(PyObjectPtr): + # Convert the int code points to unicode characters, and generate a + # local unicode instance. + # This splits surrogate pairs if sizeof(Py_UNICODE) is 2 here (in gdb). +- result = u''.join([_unichr(ucs) for ucs in Py_UNICODEs]) ++ result = u''.join([ ++ (_unichr(ucs) if ucs <= 0x10ffff else '\ufffd') ++ for ucs in Py_UNICODEs]) + return result + + def write_repr(self, out, visited): +@@ -1144,6 +1153,41 @@ class PyUnicodeObjectPtr(PyObjectPtr): + out.write(val.lstrip('u')) + + ++class wrapperobject(PyObjectPtr): ++ _typename = 'wrapperobject' ++ ++ def safe_name(self): ++ try: ++ name = self.field('descr')['d_base']['name'].string() ++ return repr(name) ++ except (NullPyObjectPtr, RuntimeError, UnicodeDecodeError): ++ return '' ++ ++ def safe_tp_name(self): ++ try: ++ return self.field('self')['ob_type']['tp_name'].string() ++ except (NullPyObjectPtr, RuntimeError, UnicodeDecodeError): ++ return '' ++ ++ def safe_self_addresss(self): ++ try: ++ address = long(self.field('self')) ++ return '%#x' % address ++ except (NullPyObjectPtr, RuntimeError): ++ return '' ++ ++ def proxyval(self, visited): ++ name = self.safe_name() ++ tp_name = self.safe_tp_name() ++ self_address = self.safe_self_addresss() ++ return ("" ++ % (name, tp_name, self_address)) ++ ++ def write_repr(self, out, visited): ++ proxy = self.proxyval(visited) ++ out.write(proxy) ++ ++ + def int_from_int(gdbval): + return int(str(gdbval)) + +@@ -1176,11 +1220,13 @@ class PyObjectPtrPrinter: + + def pretty_printer_lookup(gdbval): + type = gdbval.type.unqualified() +- if type.code == gdb.TYPE_CODE_PTR: +- type = type.target().unqualified() +- t = str(type) +- if t in ("PyObject", "PyFrameObject"): +- return PyObjectPtrPrinter(gdbval) ++ if type.code != gdb.TYPE_CODE_PTR: ++ return None ++ ++ type = type.target().unqualified() ++ t = str(type) ++ if t in ("PyObject", "PyFrameObject", "PyUnicodeObject", "wrapperobject"): ++ return PyObjectPtrPrinter(gdbval) + + """ + During development, I've been manually invoking the code in this way: +@@ -1202,7 +1248,7 @@ that this python file is installed to the same path as the library (or its + /usr/lib/debug/usr/lib/libpython2.6.so.1.0.debug-gdb.py + """ + def register (obj): +- if obj == None: ++ if obj is None: + obj = gdb + + # Wire up the pretty-printer +@@ -1304,23 +1350,43 @@ class Frame(object): + ''' + if self.is_waiting_for_gil(): + return 'Waiting for the GIL' +- elif self.is_gc_collect(): ++ ++ if self.is_gc_collect(): + return 'Garbage-collecting' +- else: +- # Detect invocations of PyCFunction instances: +- older = self.older() +- if older and older._gdbframe.name() == 'PyCFunction_Call': +- # Within that frame: +- # "func" is the local containing the PyObject* of the +- # PyCFunctionObject instance +- # "f" is the same value, but cast to (PyCFunctionObject*) +- # "self" is the (PyObject*) of the 'self' +- try: +- # Use the prettyprinter for the func: +- func = older._gdbframe.read_var('func') +- return str(func) +- except RuntimeError: +- return 'PyCFunction invocation (unable to read "func")' ++ ++ # Detect invocations of PyCFunction instances: ++ frame = self._gdbframe ++ caller = frame.name() ++ if not caller: ++ return False ++ ++ if caller == 'PyCFunction_Call': ++ arg_name = 'func' ++ # Within that frame: ++ # "func" is the local containing the PyObject* of the ++ # PyCFunctionObject instance ++ # "f" is the same value, but cast to (PyCFunctionObject*) ++ # "self" is the (PyObject*) of the 'self' ++ try: ++ # Use the prettyprinter for the func: ++ func = frame.read_var(arg_name) ++ return str(func) ++ except ValueError: ++ return ('PyCFunction invocation (unable to read %s: ' ++ 'missing debuginfos?)' % arg_name) ++ except RuntimeError: ++ return 'PyCFunction invocation (unable to read %s)' % arg_name ++ ++ if caller == 'wrapper_call': ++ arg_name = 'wp' ++ try: ++ func = frame.read_var(arg_name) ++ return str(func) ++ except ValueError: ++ return ('' % arg_name) ++ except RuntimeError: ++ return '' % arg_name + + # This frame isn't worth reporting: + return False +@@ -1368,7 +1434,11 @@ class Frame(object): + def get_selected_python_frame(cls): + '''Try to obtain the Frame for the python-related code in the selected + frame, or None''' +- frame = cls.get_selected_frame() ++ try: ++ frame = cls.get_selected_frame() ++ except gdb.error: ++ # No frame: Python didn't start yet ++ return None + + while frame: + if frame.is_python_frame(): +@@ -1509,6 +1579,10 @@ PyList() + def move_in_stack(move_up): + '''Move up or down the stack (for the py-up/py-down command)''' + frame = Frame.get_selected_python_frame() ++ if not frame: ++ print('Unable to locate python frame') ++ return ++ + while frame: + if move_up: + iter_frame = frame.older() +@@ -1571,6 +1645,10 @@ class PyBacktraceFull(gdb.Command): + + def invoke(self, args, from_tty): + frame = Frame.get_selected_python_frame() ++ if not frame: ++ print('Unable to locate python frame') ++ return ++ + while frame: + if frame.is_python_frame(): + frame.print_summary() +@@ -1588,8 +1666,12 @@ class PyBacktrace(gdb.Command): + + + def invoke(self, args, from_tty): +- sys.stdout.write('Traceback (most recent call first):\n') + frame = Frame.get_selected_python_frame() ++ if not frame: ++ print('Unable to locate python frame') ++ return ++ ++ sys.stdout.write('Traceback (most recent call first):\n') + while frame: + if frame.is_python_frame(): + frame.print_traceback() +diff --git a/Tools/msi/msi.py b/Tools/msi/msi.py +index 65ce5c153c..da4a1c3d95 100644 +--- a/Tools/msi/msi.py ++++ b/Tools/msi/msi.py +@@ -917,7 +917,7 @@ def generate_license(): + shutil.copyfileobj(open(os.path.join(srcdir, "LICENSE")), out) + shutil.copyfileobj(open("crtlicense.txt"), out) + for name, pat, file in (("bzip2","bzip2-*", "LICENSE"), +- ("Berkeley DB", "db-*", "LICENSE"), ++ ("Berkeley DB", "bsddb-*", "LICENSE"), + ("openssl", "openssl-*", "LICENSE"), + ("Tcl", "tcl-8*", "license.terms"), + ("Tk", "tk-8*", "license.terms"), +diff --git a/Tools/scripts/diff.py b/Tools/scripts/diff.py +index 513e2a7112..c4c2e101c6 100755 +--- a/Tools/scripts/diff.py ++++ b/Tools/scripts/diff.py +@@ -32,8 +32,10 @@ def main(): + + fromdate = time.ctime(os.stat(fromfile).st_mtime) + todate = time.ctime(os.stat(tofile).st_mtime) +- fromlines = open(fromfile, 'U').readlines() +- tolines = open(tofile, 'U').readlines() ++ with open(fromfile, 'U') as f: ++ fromlines = f.readlines() ++ with open(tofile, 'U') as f: ++ tolines = f.readlines() + + if options.u: + diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n) +diff --git a/Tools/scripts/patchcheck.py b/Tools/scripts/patchcheck.py +index b69d54029a..58aa168d6d 100755 +--- a/Tools/scripts/patchcheck.py ++++ b/Tools/scripts/patchcheck.py +@@ -43,20 +43,6 @@ def status(message, modal=False, info=None): + return decorated_fxn + + +-def mq_patches_applied(): +- """Check if there are any applied MQ patches.""" +- cmd = 'hg qapplied' +- st = subprocess.Popen(cmd.split(), +- stdout=subprocess.PIPE, +- stderr=subprocess.PIPE) +- try: +- bstdout, _ = st.communicate() +- return st.returncode == 0 and bstdout +- finally: +- st.stdout.close() +- st.stderr.close() +- +- + def get_git_branch(): + """Get the symbolic name for the current git branch""" + cmd = "git rev-parse --abbrev-ref HEAD".split() +@@ -101,19 +87,8 @@ def get_base_branch(): + @status("Getting the list of files that have been added/changed", + info=lambda x: n_files_str(len(x))) + def changed_files(base_branch=None): +- """Get the list of changed or added files from Mercurial or git.""" +- if os.path.isdir(os.path.join(SRCDIR, '.hg')): +- if base_branch is not None: +- sys.exit('need a git checkout to check PR status') +- cmd = 'hg status --added --modified --no-status' +- if mq_patches_applied(): +- cmd += ' --rev qparent' +- st = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) +- try: +- filenames = [x.decode().rstrip() for x in st.stdout] +- finally: +- st.stdout.close() +- elif os.path.exists(os.path.join(SRCDIR, '.git')): ++ """Get the list of changed or added files from git.""" ++ if os.path.exists(os.path.join(SRCDIR, '.git')): + # We just use an existence check here as: + # directory = normal git checkout/clone + # file = git worktree directory +@@ -138,7 +113,7 @@ def changed_files(base_branch=None): + finally: + st.stdout.close() + else: +- sys.exit('need a Mercurial or git checkout to get modified files') ++ sys.exit('need a git checkout to get modified files') + + filenames2 = [] + for filename in filenames: +@@ -221,10 +196,11 @@ def credit_given(file_paths): + return os.path.join('Misc', 'ACKS') in file_paths + + +-@status("Misc/NEWS updated", modal=True) ++@status("Misc/NEWS.d updated with `blurb`", modal=True) + def reported_news(file_paths): +- """Check if Misc/NEWS has been changed.""" +- return os.path.join('Misc', 'NEWS') in file_paths ++ """Check if Misc/NEWS.d has been changed.""" ++ return any(p.startswith(os.path.join('Misc', 'NEWS.d', 'next')) ++ for p in file_paths) + + + def main(): +@@ -234,8 +210,7 @@ def main(): + c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))] + doc_files = [fn for fn in file_paths if fn.startswith('Doc') and + fn.endswith(('.rst', '.inc'))] +- misc_files = {os.path.join('Misc', 'ACKS'), os.path.join('Misc', 'NEWS')}\ +- & set(file_paths) ++ misc_files = {p for p in file_paths if p.startswith('Misc')} + # PEP 8 whitespace rules enforcement. + normalize_whitespace(python_files) + # C rules enforcement. +diff --git a/aclocal.m4 b/aclocal.m4 +index 5fadcb1e44..5e29449ae2 100644 +--- a/aclocal.m4 ++++ b/aclocal.m4 +@@ -1,6 +1,6 @@ +-# generated automatically by aclocal 1.15 -*- Autoconf -*- ++# generated automatically by aclocal 1.15.1 -*- Autoconf -*- + +-# Copyright (C) 1996-2014 Free Software Foundation, Inc. ++# Copyright (C) 1996-2017 Free Software Foundation, Inc. + + # This file is free software; the Free Software Foundation + # gives unlimited permission to copy and/or distribute it, +@@ -12,9 +12,9 @@ + # PARTICULAR PURPOSE. + + m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) +-# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- +-# serial 11 (pkg-config-0.29.1) +- ++dnl pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- ++dnl serial 11 (pkg-config-0.29.1) ++dnl + dnl Copyright © 2004 Scott James Remnant . + dnl Copyright © 2012-2015 Dan Nicholson + dnl +@@ -288,71 +288,3 @@ AS_VAR_COPY([$1], [pkg_cv_][$1]) + AS_VAR_IF([$1], [""], [$5], [$4])dnl + ])dnl PKG_CHECK_VAR + +-dnl PKG_WITH_MODULES(VARIABLE-PREFIX, MODULES, +-dnl [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND], +-dnl [DESCRIPTION], [DEFAULT]) +-dnl ------------------------------------------ +-dnl +-dnl Prepare a "--with-" configure option using the lowercase +-dnl [VARIABLE-PREFIX] name, merging the behaviour of AC_ARG_WITH and +-dnl PKG_CHECK_MODULES in a single macro. +-AC_DEFUN([PKG_WITH_MODULES], +-[ +-m4_pushdef([with_arg], m4_tolower([$1])) +- +-m4_pushdef([description], +- [m4_default([$5], [build with ]with_arg[ support])]) +- +-m4_pushdef([def_arg], [m4_default([$6], [auto])]) +-m4_pushdef([def_action_if_found], [AS_TR_SH([with_]with_arg)=yes]) +-m4_pushdef([def_action_if_not_found], [AS_TR_SH([with_]with_arg)=no]) +- +-m4_case(def_arg, +- [yes],[m4_pushdef([with_without], [--without-]with_arg)], +- [m4_pushdef([with_without],[--with-]with_arg)]) +- +-AC_ARG_WITH(with_arg, +- AS_HELP_STRING(with_without, description[ @<:@default=]def_arg[@:>@]),, +- [AS_TR_SH([with_]with_arg)=def_arg]) +- +-AS_CASE([$AS_TR_SH([with_]with_arg)], +- [yes],[PKG_CHECK_MODULES([$1],[$2],$3,$4)], +- [auto],[PKG_CHECK_MODULES([$1],[$2], +- [m4_n([def_action_if_found]) $3], +- [m4_n([def_action_if_not_found]) $4])]) +- +-m4_popdef([with_arg]) +-m4_popdef([description]) +-m4_popdef([def_arg]) +- +-])dnl PKG_WITH_MODULES +- +-dnl PKG_HAVE_WITH_MODULES(VARIABLE-PREFIX, MODULES, +-dnl [DESCRIPTION], [DEFAULT]) +-dnl ----------------------------------------------- +-dnl +-dnl Convenience macro to trigger AM_CONDITIONAL after PKG_WITH_MODULES +-dnl check._[VARIABLE-PREFIX] is exported as make variable. +-AC_DEFUN([PKG_HAVE_WITH_MODULES], +-[ +-PKG_WITH_MODULES([$1],[$2],,,[$3],[$4]) +- +-AM_CONDITIONAL([HAVE_][$1], +- [test "$AS_TR_SH([with_]m4_tolower([$1]))" = "yes"]) +-])dnl PKG_HAVE_WITH_MODULES +- +-dnl PKG_HAVE_DEFINE_WITH_MODULES(VARIABLE-PREFIX, MODULES, +-dnl [DESCRIPTION], [DEFAULT]) +-dnl ------------------------------------------------------ +-dnl +-dnl Convenience macro to run AM_CONDITIONAL and AC_DEFINE after +-dnl PKG_WITH_MODULES check. HAVE_[VARIABLE-PREFIX] is exported as make +-dnl and preprocessor variable. +-AC_DEFUN([PKG_HAVE_DEFINE_WITH_MODULES], +-[ +-PKG_HAVE_WITH_MODULES([$1],[$2],[$3],[$4]) +- +-AS_IF([test "$AS_TR_SH([with_]m4_tolower([$1]))" = "yes"], +- [AC_DEFINE([HAVE_][$1], 1, [Enable ]m4_tolower([$1])[ support])]) +-])dnl PKG_HAVE_DEFINE_WITH_MODULES +- +diff --git a/configure.ac b/configure.ac +index 913d5469d0..5dfb824b93 100644 +--- a/configure.ac ++++ b/configure.ac +@@ -1005,9 +1005,9 @@ HAS_GIT=no-repository + fi + if test $HAS_GIT = found + then +- GITVERSION="git -C \$(srcdir) rev-parse --short HEAD" +- GITTAG="git -C \$(srcdir) describe --all --always --dirty" +- GITBRANCH="git -C \$(srcdir) name-rev --name-only HEAD" ++ GITVERSION="git --git-dir \$(srcdir)/.git rev-parse --short HEAD" ++ GITTAG="git --git-dir \$(srcdir)/.git describe --all --always --dirty" ++ GITBRANCH="git --git-dir \$(srcdir)/.git name-rev --name-only HEAD" + else + GITVERSION="" + GITTAG="" +@@ -1455,6 +1455,13 @@ if test "$Py_LTO" = 'true' ; then + esac + ;; + esac ++ ++ if test "$ac_cv_prog_cc_g" = "yes" ++ then ++ # bpo-30345: Add -g to LDFLAGS when compiling with LTO ++ # to get debug symbols. ++ LTOFLAGS="$LTOFLAGS -g" ++ fi + fi + + +@@ -3115,7 +3122,7 @@ AC_CHECK_FUNCS(alarm setitimer getitimer bind_textdomain_codeset chown \ + gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ + getentropy \ + getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \ +- initgroups kill killpg lchmod lchown lstat mkfifo mknod mktime mmap \ ++ initgroups kill killpg lchown lstat mkfifo mknod mktime mmap \ + mremap nice pathconf pause plock poll pthread_init \ + putenv readlink realpath \ + select sem_open sem_timedwait sem_getvalue sem_unlink setegid seteuid \ +@@ -3127,6 +3134,13 @@ AC_CHECK_FUNCS(alarm setitimer getitimer bind_textdomain_codeset chown \ + sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ + truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty) + ++# Force lchmod off for Linux. Linux disallows changing the mode of symbolic ++# links. Some libc implementations have a stub lchmod implementation that always ++# returns an error. ++if test "$MACHDEP" != linux; then ++ AC_CHECK_FUNC(lchmod) ++fi ++ + # For some functions, having a definition is not sufficient, since + # we want to take their address. + AC_MSG_CHECKING(for chroot) +@@ -4399,11 +4413,6 @@ then + [Define if poll() sets errno on invalid file descriptors.]) + fi + +-# Before we can test tzset, we need to check if struct tm has a tm_zone +-# (which is not required by ISO C or UNIX spec) and/or if we support +-# tzname[] +-AC_STRUCT_TIMEZONE +- + # check tzset(3) exists and works like we expect it to + AC_MSG_CHECKING(for working tzset()) + AC_CACHE_VAL(ac_cv_working_tzset, [ +diff --git a/pyconfig.h.in b/pyconfig.h.in +index 11c4a66873..f828677dda 100644 +--- a/pyconfig.h.in ++++ b/pyconfig.h.in +@@ -439,9 +439,6 @@ + /* 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 + --- python2.7-2.7.15.orig/debian/patches/hotshot-import.diff +++ python2.7-2.7.15/debian/patches/hotshot-import.diff @@ -0,0 +1,19 @@ +# DP: hotshot: Check for the availability of the profile and pstats modules. + +Index: b/Lib/hotshot/stats.py +=================================================================== +--- a/Lib/hotshot/stats.py ++++ b/Lib/hotshot/stats.py +@@ -1,7 +1,10 @@ + """Statistics analyzer for HotShot.""" + +-import profile +-import pstats ++try: ++ import profile ++ import pstats ++except ImportError, e: ++ raise ImportError, str(e) + '; please install the python-profiler package' + + import hotshot.log + --- python2.7-2.7.15.orig/debian/patches/hurd-disable-nonworking-constants.diff +++ python2.7-2.7.15/debian/patches/hurd-disable-nonworking-constants.diff @@ -0,0 +1,38 @@ +# DP: Comment out constant exposed on the API which are not implemented on +# DP: GNU/Hurd. They would not work at runtime anyway. + +Index: b/Modules/posixmodule.c +=================================================================== +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -9320,12 +9320,14 @@ all_ins(PyObject *d) + #ifdef O_LARGEFILE + if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; + #endif ++#ifndef __GNU__ + #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 ++#endif + + /* MS Windows */ + #ifdef O_NOINHERIT +Index: b/Modules/socketmodule.c +=================================================================== +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -4933,9 +4933,11 @@ init_socket(void) + #ifdef SO_OOBINLINE + PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); + #endif ++#ifndef __GNU__ + #ifdef SO_REUSEPORT + PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); + #endif ++#endif + #ifdef SO_SNDBUF + PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); + #endif --- python2.7-2.7.15.orig/debian/patches/installed-testsuite.diff +++ python2.7-2.7.15/debian/patches/installed-testsuite.diff @@ -0,0 +1,37 @@ +# DP: Changes needed to run the installed testsuite. +# DP: Also removed: +# DP: - ctypes/test/test_macholib.py +# DP: - distutils/tests/test_bdist_wininst.py + +Index: b/Lib/distutils/tests/test_build_ext.py +=================================================================== +--- a/Lib/distutils/tests/test_build_ext.py ++++ b/Lib/distutils/tests/test_build_ext.py +@@ -84,27 +84,6 @@ class BuildExtTestCase(support.TempdirMa + self.assertIsInstance(xx.Null(), xx.Null) + self.assertIsInstance(xx.Str(), xx.Str) + +- def test_solaris_enable_shared(self): +- dist = Distribution({'name': 'xx'}) +- cmd = build_ext(dist) +- old = sys.platform +- +- sys.platform = 'sunos' # fooling finalize_options +- from distutils.sysconfig import _config_vars +- old_var = _config_vars.get('Py_ENABLE_SHARED') +- _config_vars['Py_ENABLE_SHARED'] = 1 +- try: +- cmd.ensure_finalized() +- finally: +- sys.platform = old +- if old_var is None: +- del _config_vars['Py_ENABLE_SHARED'] +- else: +- _config_vars['Py_ENABLE_SHARED'] = old_var +- +- # make sure we get some library dirs under solaris +- self.assertGreater(len(cmd.library_dirs), 0) +- + @unittest.skipIf(sys.version < '2.6', + 'site.USER_SITE was introduced in 2.6') + def test_user_site(self): --- python2.7-2.7.15.orig/debian/patches/issue27239.diff +++ python2.7-2.7.15/debian/patches/issue27239.diff @@ -0,0 +1,13 @@ +Index: b/Lib/idlelib/macosxSupport.py +=================================================================== +--- a/Lib/idlelib/macosxSupport.py ++++ b/Lib/idlelib/macosxSupport.py +@@ -18,7 +18,7 @@ def isCarbonAquaTk(root): + DeprecationWarning, stacklevel=2) + return isCarbonTk() + +-_tk_type = None ++_tk_type = "other" + + def _initializeTkVariantTests(root): + """ --- python2.7-2.7.15.orig/debian/patches/issue670664.diff +++ python2.7-2.7.15/debian/patches/issue670664.diff @@ -0,0 +1,54 @@ +# DP: Proposed patch for issue #670664. + +--- a/Lib/HTMLParser.py ++++ b/Lib/HTMLParser.py +@@ -96,6 +96,7 @@ + self.rawdata = '' + self.lasttag = '???' + self.interesting = interesting_normal ++ self.cdata_tag = None + markupbase.ParserBase.reset(self) + + def feed(self, data): +@@ -120,11 +121,13 @@ + """Return full source of start tag: '<...>'.""" + return self.__starttag_text + +- def set_cdata_mode(self): ++ def set_cdata_mode(self, tag): + self.interesting = interesting_cdata ++ self.cdata_tag = tag.lower() + + def clear_cdata_mode(self): + self.interesting = interesting_normal ++ self.cdata_tag = None + + # Internal -- handle data as far as reasonable. May leave state + # and data to be processed by a subsequent call. If 'end' is +@@ -270,7 +273,7 @@ + else: + self.handle_starttag(tag, attrs) + if tag in self.CDATA_CONTENT_ELEMENTS: +- self.set_cdata_mode() ++ self.set_cdata_mode(tag) + return endpos + + # Internal -- check to see if we have a complete starttag; return end +@@ -314,10 +317,16 @@ + j = match.end() + match = endtagfind.match(rawdata, i) # + if not match: ++ if self.cdata_tag is not None: return j + self.error("bad end tag: %r" % (rawdata[i:j],)) +- tag = match.group(1) ++ tag = match.group(1).strip() ++ ++ if self.cdata_tag is not None: ++ if tag.lower() != self.cdata_tag: return j ++ + self.handle_endtag(tag.lower()) + self.clear_cdata_mode() ++ + return j + + # Overridable -- finish processing of start+end tag: --- python2.7-2.7.15.orig/debian/patches/issue9012a.diff +++ python2.7-2.7.15/debian/patches/issue9012a.diff @@ -0,0 +1,13 @@ +# DP: Link _math.o only once to the static library. + +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -169,7 +169,7 @@ + # Modules that should always be present (non UNIX dependent): + + #array arraymodule.c # array objects +-#cmath cmathmodule.c _math.c # -lm # complex math library functions ++#cmath cmathmodule.c # -lm # complex math library functions + #math mathmodule.c _math.c # -lm # math library functions, e.g. sin() + #_struct _struct.c # binary structure packing/unpacking + #time timemodule.c # -lm # time operations and variables --- python2.7-2.7.15.orig/debian/patches/issue9189.diff +++ python2.7-2.7.15/debian/patches/issue9189.diff @@ -0,0 +1,350 @@ +Index: b/Lib/sysconfig.py +=================================================================== +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -236,11 +236,19 @@ def _parse_makefile(filename, vars=None) + done[n] = v + + # do variable interpolation here +- while notdone: +- for name in notdone.keys(): ++ variables = list(notdone.keys()) ++ ++ # Variables with a 'PY_' prefix in the makefile. These need to ++ # be made available without that prefix through sysconfig. ++ # Special care is needed to ensure that variable expansion works, even ++ # if the expansion uses the name without a prefix. ++ renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') ++ ++ while len(variables) > 0: ++ for name in tuple(variables): + value = notdone[name] + m = _findvar1_rx.search(value) or _findvar2_rx.search(value) +- if m: ++ if m is not None: + n = m.group(1) + found = True + if n in done: +@@ -251,23 +259,48 @@ def _parse_makefile(filename, vars=None) + elif n in os.environ: + # do it like make: fall back to environment + item = os.environ[n] ++ ++ elif n in renamed_variables: ++ if name.startswith('PY_') and name[3:] in renamed_variables: ++ item = "" ++ ++ elif 'PY_' + n in notdone: ++ found = False ++ ++ else: ++ item = str(done['PY_' + n]) ++ + else: + done[n] = item = "" ++ + if found: + after = value[m.end():] + value = value[:m.start()] + item + after + if "$" in after: + notdone[name] = value + else: +- try: value = int(value) ++ try: ++ value = int(value) + except ValueError: + done[name] = value.strip() + else: + done[name] = value +- del notdone[name] ++ variables.remove(name) ++ ++ if name.startswith('PY_') \ ++ and name[3:] in renamed_variables: ++ ++ name = name[3:] ++ if name not in done: ++ done[name] = value ++ ++ + else: +- # bogus variable reference; just drop it since we can't deal +- del notdone[name] ++ # bogus variable reference (e.g. "prefix=$/opt/python"); ++ # just drop it since we can't deal ++ done[name] = value ++ variables.remove(name) ++ + # strip spurious spaces + for k, v in done.items(): + if isinstance(v, str): +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -72,12 +72,18 @@ MAKESETUP= $(srcdir)/Modules/makese + # Compiler options + OPT= @OPT@ + BASECFLAGS= @BASECFLAGS@ +-CFLAGS= $(BASECFLAGS) @CFLAGS@ $(OPT) $(EXTRA_CFLAGS) ++CONFIGURE_CFLAGS= @CFLAGS@ ++CONFIGURE_CPPFLAGS= @CPPFLAGS@ ++CONFIGURE_LDFLAGS= @LDFLAGS@ ++# Avoid assigning CFLAGS, LDFLAGS, etc. so users can use them on the ++# command line to append to these values without stomping the pre-set ++# values. ++PY_CFLAGS= $(BASECFLAGS) $(OPT) $(CONFIGURE_CFLAGS) $(CFLAGS) $(EXTRA_CFLAGS) + # Both CPPFLAGS and LDFLAGS need to contain the shell's value for setup.py to + # be able to build extension modules using the directories specified in the + # environment variables +-CPPFLAGS= -I. -IInclude -I$(srcdir)/Include @CPPFLAGS@ +-LDFLAGS= @LDFLAGS@ ++PY_CPPFLAGS= -I. -IInclude -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) $(CPPFLAGS) ++PY_LDFLAGS= $(CONFIGURE_LDFLAGS) $(LDFLAGS) + LDLAST= @LDLAST@ + SGI_ABI= @SGI_ABI@ + CCSHARED= @CCSHARED@ +@@ -86,7 +92,7 @@ ARFLAGS= @ARFLAGS@ + # Extra C flags added for building the interpreter object files. + CFLAGSFORSHARED=@CFLAGSFORSHARED@ + # C flags used for building the interpreter object files +-PY_CFLAGS= $(CFLAGS) $(CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE ++PY_CORE_CFLAGS= $(PY_CFLAGS) $(PY_CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE + + + # Machine-dependent subdirectories +@@ -487,7 +493,7 @@ coverage-report: regen-grammar + + # Build the interpreter + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) +- $(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \ ++ $(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \ + Modules/python.o \ + $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) + +@@ -512,7 +518,7 @@ pybuilddir.txt: $(BUILDPYTHON) + + # This is shared by the math and cmath modules + Modules/_math.o: Modules/_math.c Modules/_math.h +- $(CC) -c $(CCSHARED) $(PY_CFLAGS) -o $@ $< ++ $(CC) -c $(CCSHARED) $(PY_CORE_CFLAGS) -o $@ $< + + # Build the shared modules + # Under GNU make, MAKEFLAGS are sorted and normalized; the 's' for +@@ -523,7 +529,7 @@ sharedmods: $(BUILDPYTHON) pybuilddir.tx + *\ -s*|s*) quiet="-q";; \ + *) quiet="";; \ + esac; \ +- $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' \ ++ $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(PY_LDFLAGS)' OPT='$(OPT)' \ + _TCLTK_INCLUDES='$(TCLTK_INCLUDES)' _TCLTK_LIBS='$(TCLTK_LIBS)' \ + $(PYTHON_FOR_BUILD) $(srcdir)/setup.py $$quiet build + +@@ -541,18 +547,18 @@ $(LIBRARY): $(LIBRARY_OBJS) + + libpython$(VERSION).so: $(LIBRARY_OBJS) + if test $(INSTSONAME) != $(LDLIBRARY); then \ +- $(BLDSHARED) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(BLDSHARED) $(PY_LDFLAGS) $(CCSHARED) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LN) -f $(INSTSONAME) $@; \ + else \ +- $(BLDSHARED) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(BLDSHARED) $(PY_LDFLAGS) $(CCSHARED) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + fi + + libpython$(VERSION).dylib: $(LIBRARY_OBJS) +- $(CC) -dynamiclib -Wl,-single_module $(LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(CC) -dynamiclib -Wl,-single_module $(PY_LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + + + libpython$(VERSION).sl: $(LIBRARY_OBJS) +- $(LDSHARED) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST) ++ $(LDSHARED) $(PY_LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST) + + # Copy up the gdb python hooks into a position where they can be automatically + # loaded by gdb during Lib/test/test_gdb.py +@@ -591,7 +597,7 @@ $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION + # for a shared core library; otherwise, this rule is a noop. + $(DLLLIBRARY) libpython$(VERSION).dll.a: $(LIBRARY_OBJS) + if test -n "$(DLLLIBRARY)"; then \ +- $(LDSHARED) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \ ++ $(LDSHARED) $(PY_LDFLAGS) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \ + $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST); \ + else true; \ + fi +@@ -641,14 +647,14 @@ Modules/getbuildinfo.o: $(PARSER_OBJS) \ + $(SIGNAL_OBJS) \ + $(MODOBJS) \ + $(srcdir)/Modules/getbuildinfo.c +- $(CC) -c $(PY_CFLAGS) \ ++ $(CC) -c $(PY_CORE_CFLAGS) \ + -DGITVERSION="\"`LC_ALL=C $(GITVERSION)`\"" \ + -DGITTAG="\"`LC_ALL=C $(GITTAG)`\"" \ + -DGITBRANCH="\"`LC_ALL=C $(GITBRANCH)`\"" \ + -o $@ $(srcdir)/Modules/getbuildinfo.c + + Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile +- $(CC) -c $(PY_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \ ++ $(CC) -c $(PY_CORE_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \ + -DPREFIX='"$(prefix)"' \ + -DEXEC_PREFIX='"$(exec_prefix)"' \ + -DVERSION='"$(VERSION)"' \ +@@ -656,7 +662,7 @@ Modules/getpath.o: $(srcdir)/Modules/get + -o $@ $(srcdir)/Modules/getpath.c + + Modules/python.o: $(srcdir)/Modules/python.c +- $(MAINCC) -c $(PY_CFLAGS) -o $@ $(srcdir)/Modules/python.c ++ $(MAINCC) -c $(PY_CORE_CFLAGS) -o $@ $(srcdir)/Modules/python.c + + Modules/posixmodule.o: $(srcdir)/Modules/posixmodule.c $(srcdir)/Modules/posixmodule.h + +@@ -665,7 +671,7 @@ Modules/grpmodule.o: $(srcdir)/Modules/g + Modules/pwdmodule.o: $(srcdir)/Modules/pwdmodule.c $(srcdir)/Modules/posixmodule.h + + $(PGEN): $(PGENOBJS) +- $(CC) $(OPT) $(LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN) ++ $(CC) $(OPT) $(PY_LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN) + + .PHONY: regen-grammar + regen-grammar: $(PGEN) +@@ -701,10 +707,10 @@ regen-ast: + Python/compile.o Python/symtable.o Python/ast.o: $(srcdir)/Include/graminit.h $(srcdir)/Include/Python-ast.h + + Python/getplatform.o: $(srcdir)/Python/getplatform.c +- $(CC) -c $(PY_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c ++ $(CC) -c $(PY_CORE_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c + + Python/importdl.o: $(srcdir)/Python/importdl.c +- $(CC) -c $(PY_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c ++ $(CC) -c $(PY_CORE_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c + + Objects/unicodectype.o: $(srcdir)/Objects/unicodectype.c \ + $(srcdir)/Objects/unicodetype_db.h +@@ -1356,7 +1362,7 @@ config.status: $(srcdir)/configure + + # Some make's put the object file in the current directory + .c.o: +- $(CC) -c $(PY_CFLAGS) -o $@ $< ++ $(CC) -c $(PY_CORE_CFLAGS) -o $@ $< + + # Run reindent on the library + reindent: +Index: b/Modules/makesetup +=================================================================== +--- a/Modules/makesetup ++++ b/Modules/makesetup +@@ -219,7 +219,7 @@ sed -e 's/[ ]*#.*//' -e '/^[ ]*$/d' | + case $doconfig in + no) cc="$cc \$(CCSHARED) \$(CFLAGS) \$(CPPFLAGS)";; + *) +- cc="$cc \$(PY_CFLAGS)";; ++ cc="$cc \$(PY_CORE_CFLAGS)";; + esac + rule="$obj: $src; $cc $cpps -c $src -o $obj" + echo "$rule" >>$rulesf +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -647,14 +647,13 @@ if test "$MACHDEP" = "irix6" && test "$C + fi + fi + +-# If the user set CFLAGS, use this instead of the automatically +-# determined setting +-preset_cflags="$CFLAGS" +-AC_PROG_CC +-if test ! -z "$preset_cflags" +-then +- CFLAGS=$preset_cflags ++# Don't let AC_PROG_CC set the default CFLAGS. It normally sets -g -O2 ++# when the compiler supports them, but we don't always want -O2, and ++# we set -g later. ++if test -z "$CFLAGS"; then ++ CFLAGS= + fi ++AC_PROG_CC + + AC_SUBST(CXX) + AC_SUBST(MAINCC) +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -320,11 +320,19 @@ def parse_makefile(fn, g=None): + done[n] = v + + # do variable interpolation here +- while notdone: +- for name in notdone.keys(): ++ variables = list(notdone.keys()) ++ ++ # Variables with a 'PY_' prefix in the makefile. These need to ++ # be made available without that prefix through sysconfig. ++ # Special care is needed to ensure that variable expansion works, even ++ # if the expansion uses the name without a prefix. ++ renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') ++ ++ while len(variables) > 0: ++ for name in tuple(variables): + value = notdone[name] + m = _findvar1_rx.search(value) or _findvar2_rx.search(value) +- if m: ++ if m is not None: + n = m.group(1) + found = True + if n in done: +@@ -335,25 +343,47 @@ def parse_makefile(fn, g=None): + elif n in os.environ: + # do it like make: fall back to environment + item = os.environ[n] ++ ++ elif n in renamed_variables: ++ if name.startswith('PY_') and name[3:] in renamed_variables: ++ item = "" ++ ++ elif 'PY_' + n in notdone: ++ found = False ++ ++ else: ++ item = str(done['PY_' + n]) ++ + else: + done[n] = item = "" ++ + if found: + after = value[m.end():] + value = value[:m.start()] + item + after + if "$" in after: + notdone[name] = value + else: +- try: value = int(value) ++ try: ++ value = int(value) + except ValueError: + done[name] = value.strip() + else: + done[name] = value +- del notdone[name] +- else: +- # bogus variable reference; just drop it since we can't deal +- del notdone[name] ++ variables.remove(name) ++ ++ if name.startswith('PY_') \ ++ and name[3:] in renamed_variables: + +- fp.close() ++ name = name[3:] ++ if name not in done: ++ done[name] = value ++ ++ ++ else: ++ # bogus variable reference (e.g. "prefix=$/opt/python"); ++ # just drop it since we can't deal ++ done[name] = value ++ variables.remove(name) + + # strip spurious spaces + for k, v in done.items(): --- python2.7-2.7.15.orig/debian/patches/langpack-gettext.diff +++ python2.7-2.7.15/debian/patches/langpack-gettext.diff @@ -0,0 +1,36 @@ +# DP: Description: support alternative gettext tree in +# DP: /usr/share/locale-langpack; if a file is present in both trees, +# DP: prefer the newer one +# DP: Upstream status: Ubuntu-Specific + +Index: b/Lib/gettext.py +=================================================================== +--- a/Lib/gettext.py ++++ b/Lib/gettext.py +@@ -522,11 +522,26 @@ def find(domain, localedir=None, languag + if lang == 'C': + break + mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) ++ mofile_lp = os.path.join("/usr/share/locale-langpack", lang, ++ 'LC_MESSAGES', '%s.mo' % domain) ++ ++ # first look into the standard locale dir, then into the ++ # langpack locale dir ++ ++ # standard mo file + if os.path.exists(mofile): + if all: + result.append(mofile) + else: + return mofile ++ ++ # langpack mofile -> use it ++ if os.path.exists(mofile_lp): ++ if all: ++ result.append(mofile_lp) ++ else: ++ return mofile_lp ++ + return result + + --- python2.7-2.7.15.orig/debian/patches/lib2to3-no-pickled-grammar.diff +++ python2.7-2.7.15/debian/patches/lib2to3-no-pickled-grammar.diff @@ -0,0 +1,159 @@ +Index: b/Lib/lib2to3/pgen2/driver.py +=================================================================== +--- a/Lib/lib2to3/pgen2/driver.py ++++ b/Lib/lib2to3/pgen2/driver.py +@@ -123,7 +123,10 @@ def load_grammar(gt="Grammar.txt", gp=No + if force or not _newer(gp, gt): + logger.info("Generating grammar tables from %s", gt) + g = pgen.generate_grammar(gt) +- if save: ++ # the pickle files mismatch, when built on different architectures. ++ # don't save these for now. An alternative solution might be to ++ # include the multiarch triplet into the file name ++ if False: + logger.info("Writing grammar tables to %s", gp) + try: + g.dump(gp) +Index: b/Lib/lib2to3/tests/test_main.py +=================================================================== +--- a/Lib/lib2to3/tests/test_main.py ++++ b/Lib/lib2to3/tests/test_main.py +@@ -82,68 +82,6 @@ class TestMain(unittest.TestCase): + trivial.write("print 'I need a simple conversion.'") + self.setup_files.append("trivial.py") + +- def test_filename_changing_on_output_single_dir(self): +- """2to3 a single directory with a new output dir and suffix.""" +- self.setup_test_source_trees() +- out = StringIO.StringIO() +- err = StringIO.StringIO() +- suffix = "TEST" +- ret = self.run_2to3_capture( +- ["-n", "--add-suffix", suffix, "--write-unchanged-files", +- "--no-diffs", "--output-dir", +- self.py3_dest_dir, self.py2_src_dir], +- StringIO.StringIO(""), out, err) +- self.assertEqual(ret, 0) +- stderr = err.getvalue() +- self.assertIn(" implies -w.", stderr) +- self.assertIn( +- "Output in %r will mirror the input directory %r layout" % ( +- self.py3_dest_dir, self.py2_src_dir), stderr) +- self.assertEqual(set(name+suffix for name in self.setup_files), +- set(os.listdir(self.py3_dest_dir))) +- for name in self.setup_files: +- self.assertIn("Writing converted %s to %s" % ( +- os.path.join(self.py2_src_dir, name), +- os.path.join(self.py3_dest_dir, name+suffix)), stderr) +- sep = re.escape(os.sep) +- self.assertRegexpMatches( +- stderr, r"No changes to .*/__init__\.py".replace("/", sep)) +- self.assertNotRegex( +- stderr, r"No changes to .*/trivial\.py".replace("/", sep)) +- +- def test_filename_changing_on_output_two_files(self): +- """2to3 two files in one directory with a new output dir.""" +- self.setup_test_source_trees() +- err = StringIO.StringIO() +- py2_files = [self.trivial_py2_file, self.init_py2_file] +- expected_files = set(os.path.basename(name) for name in py2_files) +- ret = self.run_2to3_capture( +- ["-n", "-w", "--write-unchanged-files", +- "--no-diffs", "--output-dir", self.py3_dest_dir] + py2_files, +- StringIO.StringIO(""), StringIO.StringIO(), err) +- self.assertEqual(ret, 0) +- stderr = err.getvalue() +- self.assertIn( +- "Output in %r will mirror the input directory %r layout" % ( +- self.py3_dest_dir, self.py2_src_dir), stderr) +- self.assertEqual(expected_files, set(os.listdir(self.py3_dest_dir))) +- +- def test_filename_changing_on_output_single_file(self): +- """2to3 a single file with a new output dir.""" +- self.setup_test_source_trees() +- err = StringIO.StringIO() +- ret = self.run_2to3_capture( +- ["-n", "-w", "--no-diffs", "--output-dir", self.py3_dest_dir, +- self.trivial_py2_file], +- StringIO.StringIO(""), StringIO.StringIO(), err) +- self.assertEqual(ret, 0) +- stderr = err.getvalue() +- self.assertIn( +- "Output in %r will mirror the input directory %r layout" % ( +- self.py3_dest_dir, self.py2_src_dir), stderr) +- self.assertEqual(set([os.path.basename(self.trivial_py2_file)]), +- set(os.listdir(self.py3_dest_dir))) +- + + if __name__ == '__main__': + unittest.main() +Index: b/Lib/lib2to3/tests/test_parser.py +=================================================================== +--- a/Lib/lib2to3/tests/test_parser.py ++++ b/Lib/lib2to3/tests/test_parser.py +@@ -41,65 +41,6 @@ class TestPgen2Caching(support.TestCase) + def test_load_grammar_from_txt_file(self): + pgen2_driver.load_grammar(support.grammar_path, save=False, force=True) + +- def test_load_grammar_from_pickle(self): +- # Make a copy of the grammar file in a temp directory we are +- # guaranteed to be able to write to. +- tmpdir = tempfile.mkdtemp() +- try: +- grammar_copy = os.path.join( +- tmpdir, os.path.basename(support.grammar_path)) +- shutil.copy(support.grammar_path, grammar_copy) +- pickle_name = pgen2_driver._generate_pickle_name(grammar_copy) +- +- pgen2_driver.load_grammar(grammar_copy, save=True, force=True) +- self.assertTrue(os.path.exists(pickle_name)) +- +- os.unlink(grammar_copy) # Only the pickle remains... +- pgen2_driver.load_grammar(grammar_copy, save=False, force=False) +- finally: +- shutil.rmtree(tmpdir) +- +- @unittest.skipIf(sys.executable is None, 'sys.executable required') +- def test_load_grammar_from_subprocess(self): +- tmpdir = tempfile.mkdtemp() +- tmpsubdir = os.path.join(tmpdir, 'subdir') +- try: +- os.mkdir(tmpsubdir) +- grammar_base = os.path.basename(support.grammar_path) +- grammar_copy = os.path.join(tmpdir, grammar_base) +- grammar_sub_copy = os.path.join(tmpsubdir, grammar_base) +- shutil.copy(support.grammar_path, grammar_copy) +- shutil.copy(support.grammar_path, grammar_sub_copy) +- pickle_name = pgen2_driver._generate_pickle_name(grammar_copy) +- pickle_sub_name = pgen2_driver._generate_pickle_name( +- grammar_sub_copy) +- self.assertNotEqual(pickle_name, pickle_sub_name) +- +- # Generate a pickle file from this process. +- pgen2_driver.load_grammar(grammar_copy, save=True, force=True) +- self.assertTrue(os.path.exists(pickle_name)) +- +- # Generate a new pickle file in a subprocess with a most likely +- # different hash randomization seed. +- sub_env = dict(os.environ) +- sub_env['PYTHONHASHSEED'] = 'random' +- subprocess.check_call( +- [sys.executable, '-c', """ +-from lib2to3.pgen2 import driver as pgen2_driver +-pgen2_driver.load_grammar(%r, save=True, force=True) +- """ % (grammar_sub_copy,)], +- env=sub_env) +- self.assertTrue(os.path.exists(pickle_sub_name)) +- +- with open(pickle_name, 'rb') as pickle_f_1, \ +- open(pickle_sub_name, 'rb') as pickle_f_2: +- self.assertEqual( +- pickle_f_1.read(), pickle_f_2.read(), +- msg='Grammar caches generated using different hash seeds' +- ' were not identical.') +- finally: +- shutil.rmtree(tmpdir) +- + def test_load_packaged_grammar(self): + modname = __name__ + '.load_test' + class MyLoader: --- python2.7-2.7.15.orig/debian/patches/libffi-shared.diff +++ python2.7-2.7.15/debian/patches/libffi-shared.diff @@ -0,0 +1,13 @@ +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -2145,7 +2145,7 @@ class PyBuildExt(build_ext): + 'ffi_wrapper_h'.format(ffi_h)) + ffi_lib = None + if ffi_inc is not None: +- for lib_name in ('ffi_convenience', 'ffi_pic', 'ffi'): ++ for lib_name in ('ffi', 'ffi_convenience', 'ffi_pic', 'ffi'): + if (self.compiler.find_library_file(lib_dirs, lib_name)): + ffi_lib = lib_name + break --- python2.7-2.7.15.orig/debian/patches/libre.diff +++ python2.7-2.7.15/debian/patches/libre.diff @@ -0,0 +1,9 @@ +--- Doc/lib/libre.tex~ 2003-07-25 09:29:22.000000000 +0200 ++++ Doc/lib/libre.tex 2003-07-25 09:30:58.000000000 +0200 +@@ -919,5 +919,5 @@ + Starting with Python 2.3, simple uses of the \regexp{*?} pattern are + special-cased to avoid recursion. Thus, the above regular expression + can avoid recursion by being recast as +-\regexp{Begin [a-zA-Z0-9_ ]*?end}. As a further benefit, such regular ++`Begin [a-zA-Z0-9_ ]*?end'. As a further benefit, such regular + expressions will run faster than their recursive equivalents. --- python2.7-2.7.15.orig/debian/patches/link-opt.diff +++ python2.7-2.7.15/debian/patches/link-opt.diff @@ -0,0 +1,26 @@ +# DP: Call the linker with -O1 -Bsymbolic-functions + +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -2240,8 +2240,8 @@ then + fi + ;; + Linux*|GNU*|QNX*) +- LDSHARED='$(CC) -shared' +- LDCXXSHARED='$(CXX) -shared';; ++ LDSHARED='$(CC) -shared -Wl,-O1 -Wl,-Bsymbolic-functions' ++ LDCXXSHARED='$(CXX) -shared -Wl,-O1 -Wl,-Bsymbolic-functions';; + BSD/OS*/4*) + LDSHARED="gcc -shared" + LDCXXSHARED="g++ -shared";; +@@ -2343,7 +2343,7 @@ then + LINKFORSHARED="-Wl,-E -Wl,+s";; + # LINKFORSHARED="-Wl,-E -Wl,+s -Wl,+b\$(BINLIBDEST)/lib-dynload";; + BSD/OS/4*) LINKFORSHARED="-Xlinker -export-dynamic";; +- Linux*|GNU*) LINKFORSHARED="-Xlinker -export-dynamic";; ++ Linux*|GNU*) LINKFORSHARED="-Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions";; + # -u libsys_s pulls in all symbols in libsys + Darwin/*) + # -u _PyMac_Error is needed to pull in the mac toolbox glue, --- python2.7-2.7.15.orig/debian/patches/link-system-expat.diff +++ python2.7-2.7.15/debian/patches/link-system-expat.diff @@ -0,0 +1,24 @@ +# DP: Link with the system expat + +Index: b/Modules/Setup.dist +=================================================================== +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -181,7 +181,7 @@ GLHACK=-Dclear=__GLclear + #itertools itertoolsmodule.c # Functions creating iterators for efficient looping + #strop stropmodule.c # String manipulations + #_functools _functoolsmodule.c # Tools for working with functions and callable objects +-#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator ++#_elementtree -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator + #_pickle _pickle.c # pickle accelerator + #datetime datetimemodule.c # date/time type + #_bisect _bisectmodule.c # Bisection algorithms +@@ -467,7 +467,7 @@ GLHACK=-Dclear=__GLclear + # Interface to the Expat XML parser + # More information on Expat can be found at www.libexpat.org. + # +-#pyexpat expat/xmlparse.c expat/xmlrole.c expat/xmltok.c pyexpat.c -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI ++#pyexpat pyexpat.c -lexpat + + + # Hye-Shik Chang's CJKCodecs --- python2.7-2.7.15.orig/debian/patches/link-whole-archive.diff +++ python2.7-2.7.15/debian/patches/link-whole-archive.diff @@ -0,0 +1,15 @@ +# DP: Link libpython with --whole-archive. + +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -497,7 +497,7 @@ coverage-report: regen-grammar + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) + $(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \ + Modules/python.o \ +- $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) ++ -Wl,--whole-archive $(BLDLIBRARY) -Wl,--no-whole-archive $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) + + platform: $(BUILDPYTHON) pybuilddir.txt + $(RUNSHARED) $(PYTHON_FOR_BUILD) -c 'import sys ; from sysconfig import get_platform ; print get_platform()+"-"+sys.version[0:3]' >platform --- python2.7-2.7.15.orig/debian/patches/local-doc-references.diff +++ python2.7-2.7.15/debian/patches/local-doc-references.diff @@ -0,0 +1,27 @@ +Index: b/Doc/tools/templates/layout.html +=================================================================== +--- a/Doc/tools/templates/layout.html ++++ b/Doc/tools/templates/layout.html +@@ -17,7 +17,7 @@ + {% block relbar2 %} {% if builder != 'qthelp' %} {{ relbar() }} {% endif %} {% endblock %} + {% block extrahead %} + +- ++ + {% if not embedded %}{% endif %} + {% if switchers is defined and not embedded %}{% endif %} + {{ super() }} +Index: b/Misc/python.man +=================================================================== +--- a/Misc/python.man ++++ b/Misc/python.man +@@ -456,7 +456,8 @@ The Python Software Foundation: https:// + .SH INTERNET RESOURCES + Main website: https://www.python.org/ + .br +-Documentation: https://docs.python.org/2/ ++Documentation: file:///usr/share/doc/python2.7/html/index.html (python-doc package) ++or https://docs.python.org/2/ + .br + Developer resources: https://docs.python.org/devguide/ + .br --- python2.7-2.7.15.orig/debian/patches/locale-module.diff +++ python2.7-2.7.15/debian/patches/locale-module.diff @@ -0,0 +1,19 @@ +# DP: * Lib/locale.py: +# DP: - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding +# DP: for glibc. + +Index: b/Lib/locale.py +=================================================================== +--- a/Lib/locale.py ++++ b/Lib/locale.py +@@ -1761,8 +1761,8 @@ locale_alias = { + 'uk_ua.iso88595': 'uk_UA.ISO8859-5', + 'uk_ua.koi8u': 'uk_UA.KOI8-U', + 'uk_ua.microsoftcp1251': 'uk_UA.CP1251', +- 'univ': 'en_US.utf', +- 'universal': 'en_US.utf', ++ 'univ': 'en_US.UTF-8', ++ 'universal': 'en_US.UTF-8', + 'universal.utf8@ucs4': 'en_US.UTF-8', + 'unm_us': 'unm_US.UTF-8', + 'ur': 'ur_PK.CP1256', --- python2.7-2.7.15.orig/debian/patches/lto-link-flags.diff +++ python2.7-2.7.15/debian/patches/lto-link-flags.diff @@ -0,0 +1,24 @@ +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -127,8 +127,8 @@ LIBP= $(LIBDIR)/python$(VERSION) + + # Symbols used for using shared libraries + SO= @SO@ +-LDSHARED= @LDSHARED@ $(LDFLAGS) +-BLDSHARED= @BLDSHARED@ $(LDFLAGS) ++LDSHARED= @LDSHARED@ $(PY_LDFLAGS) ++BLDSHARED= @BLDSHARED@ $(PY_LDFLAGS) $(PY_CFLAGS) + LDCXXSHARED= @LDCXXSHARED@ + DESTSHARED= $(BINLIBDEST)/lib-dynload + +@@ -495,7 +495,7 @@ coverage-report: regen-grammar + + # Build the interpreter + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) +- $(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \ ++ $(LINKCC) $(PY_LDFLAGS) $(PY_CFLAGS) $(LINKFORSHARED) -o $@ \ + Modules/python.o \ + -Wl,--whole-archive $(BLDLIBRARY) -Wl,--no-whole-archive $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) + --- python2.7-2.7.15.orig/debian/patches/m-i-p-s-r6.diff +++ python2.7-2.7.15/debian/patches/m-i-p-s-r6.diff @@ -0,0 +1,24 @@ +--- a/Modules/_ctypes/libffi/config.sub ++++ b/Modules/_ctypes/libffi/config.sub +@@ -282,8 +282,10 @@ case $basic_machine in + | mips64vr5900 | mips64vr5900el \ + | mipsisa32 | mipsisa32el \ + | mipsisa32r2 | mipsisa32r2el \ ++ | mipsisa32r6 | mipsisa32r6el \ + | mipsisa64 | mipsisa64el \ + | mipsisa64r2 | mipsisa64r2el \ ++ | mipsisa64r6 | mipsisa64r6el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ + | mipsr5900 | mipsr5900el \ +@@ -400,8 +402,10 @@ case $basic_machine in + | mips64vr5900-* | mips64vr5900el-* \ + | mipsisa32-* | mipsisa32el-* \ + | mipsisa32r2-* | mipsisa32r2el-* \ ++ | mipsisa32r6-* | mipsisa32r6el-* \ + | mipsisa64-* | mipsisa64el-* \ + | mipsisa64r2-* | mipsisa64r2el-* \ ++ | mipsisa64r6-* | mipsisa64r6el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ + | mipsr5900-* | mipsr5900el-* \ --- python2.7-2.7.15.orig/debian/patches/makesetup-bashism.diff +++ python2.7-2.7.15/debian/patches/makesetup-bashism.diff @@ -0,0 +1,13 @@ +# DP: Fix bashism in makesetup shell script + +--- a/Modules/makesetup ++++ b/Modules/makesetup +@@ -281,7 +281,7 @@ + -) ;; + *) sedf="@sed.in.$$" + trap 'rm -f $sedf' 0 1 2 3 +- echo "1i\\" >$sedf ++ printf "1i\\" >$sedf + str="# Generated automatically from $makepre by makesetup." + echo "$str" >>$sedf + echo "s%_MODOBJS_%$OBJS%" >>$sedf --- python2.7-2.7.15.orig/debian/patches/mangle-fstack-protector.diff +++ python2.7-2.7.15/debian/patches/mangle-fstack-protector.diff @@ -0,0 +1,24 @@ +# DP: When using GCC versions older than 4.9, automagically mangle +# DP: -fstack-protector-strong to -fstack-protector + +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -15,6 +15,7 @@ import os + import re + import string + import sys ++import fnmatch + + from distutils.errors import DistutilsPlatformError + +@@ -197,6 +198,10 @@ def customize_compiler(compiler): + cc = newcc + if 'CXX' in os.environ: + cxx = os.environ['CXX'] ++ if fnmatch.filter([cc, cxx], '*-4.[0-8]'): ++ configure_cflags = configure_cflags.replace('-fstack-protector-strong', '-fstack-protector') ++ ldshared = ldshared.replace('-fstack-protector-strong', '-fstack-protector') ++ cflags = cflags.replace('-fstack-protector-strong', '-fstack-protector') + if 'LDSHARED' in os.environ: + ldshared = os.environ['LDSHARED'] + if 'CPP' in os.environ: --- python2.7-2.7.15.orig/debian/patches/multiarch.diff +++ python2.7-2.7.15/debian/patches/multiarch.diff @@ -0,0 +1,166 @@ +Index: b/Lib/sysconfig.py +=================================================================== +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -338,7 +338,7 @@ def get_makefile_filename(): + """Return the path of the Makefile.""" + if _PYTHON_BUILD: + return os.path.join(_PROJECT_BASE, "Makefile") +- return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config" + (sys.pydebug and "_d" or ""), "Makefile") ++ return os.path.join(get_config_var('LIBPL'), "Makefile") + + # Issue #22199: retain undocumented private name for compatibility + _get_makefile_filename = get_makefile_filename +@@ -537,6 +537,12 @@ def get_config_vars(*args): + # the init-function. + _CONFIG_VARS['userbase'] = _getuserbase() + ++ multiarch = get_config_var('MULTIARCH') ++ if multiarch: ++ _CONFIG_VARS['multiarchsubdir'] = '/' + multiarch ++ else: ++ _CONFIG_VARS['multiarchsubdir'] = '' ++ + if 'srcdir' not in _CONFIG_VARS: + _CONFIG_VARS['srcdir'] = _PROJECT_BASE + +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -101,6 +101,9 @@ MACHDEP= @MACHDEP@ + # Multiarch directory (may be empty) + MULTIARCH= @MULTIARCH@ + ++# Multiarch directory (may be empty) ++MULTIARCH= @MULTIARCH@ ++ + # Install prefix for architecture-independent files + prefix= @prefix@ + +@@ -622,6 +625,10 @@ Makefile Modules/config.c: Makefile.pre + @mv config.c Modules + @echo "The Makefile was updated, you may need to re-run make." + ++Python/dynload_shlib.o: $(srcdir)/Python/dynload_shlib.c Makefile ++ $(CC) -c $(PY_CORE_CFLAGS) \ ++ $(if $(MULTIARCH),-DMULTIARCH='"$(MULTIARCH)"') \ ++ -o $@ $(srcdir)/Python/dynload_shlib.c + + Modules/Setup: $(srcdir)/Modules/Setup.dist + @if test -f Modules/Setup; then \ +@@ -1204,10 +1211,10 @@ inclinstall: + + # Install the library and miscellaneous stuff needed for extending/embedding + # This goes into $(exec_prefix)$(DEBUG_EXT) +-LIBPL= $(LIBP)/config$(DEBUG_EXT) ++LIBPL= $(LIBP)/config-$(MULTIARCH)$(DEBUG_EXT) + + # pkgconfig directory +-LIBPC= $(LIBDIR)/pkgconfig ++LIBPC= $(LIBDIR)/$(MULTIARCH)/pkgconfig + + libainstall: @DEF_MAKE_RULE@ python-config + @for i in $(LIBDIR) $(LIBP) $(LIBPL) $(LIBPC); \ +@@ -1487,6 +1494,11 @@ patchcheck: + + Python/thread.o: @THREADHEADERS@ + ++Python/sysmodule.o: $(srcdir)/Python/sysmodule.c Makefile ++ $(CC) -c $(PY_CORE_CFLAGS) \ ++ -DMULTIARCH='"$(MULTIARCH)"' \ ++ -o $@ $(srcdir)/Python/sysmodule.c ++ + # Declare targets that aren't real files + .PHONY: all build_all sharedmods check-clean-src oldsharedmods test quicktest memtest + .PHONY: install altinstall oldsharedinstall bininstall altbininstall +Index: b/Python/dynload_shlib.c +=================================================================== +--- a/Python/dynload_shlib.c ++++ b/Python/dynload_shlib.c +@@ -49,6 +49,12 @@ const struct filedescr _PyImport_DynLoad + #ifdef Py_DEBUG + {"_d.so", "rb", C_EXTENSION}, + {"module_d.so", "rb", C_EXTENSION}, ++# ifdef MULTIARCH ++ {"." MULTIARCH "_d.so", "rb", C_EXTENSION}, ++# endif ++#endif ++#ifdef MULTIARCH ++ {"." MULTIARCH ".so", "rb", C_EXTENSION}, + #endif + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -511,8 +511,16 @@ then + fi + AC_MSG_RESULT($MACHDEP) + ++MULTIARCH=$($CC --print-multiarch 2>/dev/null) ++AC_SUBST(MULTIARCH) ++ ++ + AC_SUBST(PLATDIR) +-PLATDIR=plat-$MACHDEP ++if test -n "$MULTIARCH"; then ++ PLATDIR=plat-$MULTIARCH ++else ++ PLATDIR=plat-$MACHDEP ++fi + + # And add extra plat-mac for darwin + AC_SUBST(EXTRAPLATDIR) +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -74,8 +74,6 @@ def get_python_inc(plat_specific=0, pref + If 'prefix' is supplied, use it instead of sys.prefix or + sys.exec_prefix -- i.e., ignore 'plat_specific'. + """ +- if prefix is None: +- prefix = plat_specific and EXEC_PREFIX or PREFIX + + if os.name == "posix": + if python_build: +@@ -90,7 +88,14 @@ def get_python_inc(plat_specific=0, pref + # Include is located in the srcdir + inc_dir = os.path.join(srcdir, "Include") + return inc_dir +- return os.path.join(prefix, "include", "python" + get_python_version())+(sys.pydebug and "_d" or "") ++ else: ++ if not (prefix is None): ++ return os.path.join(prefix, "include", ++ "python" + get_python_version())+(sys.pydebug and "_d" or "") ++ if plat_specific: ++ return get_config_var('CONFINCLUDEPY') ++ else: ++ return get_config_var('INCLUDEPY') + elif os.name == "nt": + return os.path.join(prefix, "include") + elif os.name == "os2": +@@ -263,7 +268,7 @@ def get_makefile_filename(): + if python_build: + return os.path.join(project_base, "Makefile") + lib_dir = get_python_lib(plat_specific=1, standard_lib=1) +- return os.path.join(lib_dir, "config"+(sys.pydebug and "_d" or ""), "Makefile") ++ return os.path.join(get_config_var('LIBPL'), "Makefile") + + + def parse_config_h(fp, g=None): +Index: b/Python/sysmodule.c +=================================================================== +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1453,6 +1453,8 @@ _PySys_Init(void) + PyFloat_GetInfo()); + SET_SYS_FROM_STRING("long_info", + PyLong_GetInfo()); ++ SET_SYS_FROM_STRING("_multiarch", ++ PyString_FromString(MULTIARCH)); + #ifdef Py_USING_UNICODE + SET_SYS_FROM_STRING("maxunicode", + PyInt_FromLong(PyUnicode_GetMax())); --- python2.7-2.7.15.orig/debian/patches/no-large-file-support.diff +++ python2.7-2.7.15/debian/patches/no-large-file-support.diff @@ -0,0 +1,14 @@ +# DP: disable large file support for GNU/Hurd + +--- a/configure.ac ++++ b/configure.ac +@@ -1434,6 +1434,9 @@ + use_lfs=no + fi + ++# Don't use largefile support anyway. ++use_lfs=no ++ + if test "$use_lfs" = "yes"; then + # Two defines needed to enable largefile support on various platforms + # These may affect some typedefs --- python2.7-2.7.15.orig/debian/patches/no-zip-on-sys.path.diff +++ python2.7-2.7.15/debian/patches/no-zip-on-sys.path.diff @@ -0,0 +1,54 @@ +# DP: Do not add /usr/lib/pythonXY.zip on sys.path. + +Index: b/Modules/getpath.c +=================================================================== +--- a/Modules/getpath.c ++++ b/Modules/getpath.c +@@ -372,7 +372,9 @@ calculate_path(void) + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); + char argv0_path[MAXPATHLEN+1]; ++#ifdef WITH_ZIP_PATH + char zip_path[MAXPATHLEN+1]; ++#endif + int pfound, efound; /* 1 if found; -1 if found build directory */ + char *buf; + size_t bufsz; +@@ -512,6 +514,7 @@ calculate_path(void) + else + reduce(prefix); + ++#ifdef WITH_ZIP_PATH + strncpy(zip_path, prefix, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ +@@ -524,6 +527,7 @@ calculate_path(void) + bufsz = strlen(zip_path); /* Replace "00" with version */ + zip_path[bufsz - 6] = VERSION[0]; + zip_path[bufsz - 5] = VERSION[2]; ++#endif + + if (!(efound = search_for_exec_prefix(argv0_path, home))) { + if (!Py_FrozenFlag) +@@ -563,7 +567,9 @@ calculate_path(void) + defpath = delim + 1; + } + ++#ifdef WITH_ZIP_PATH + bufsz += strlen(zip_path) + 1; ++#endif + bufsz += strlen(exec_prefix) + 1; + + /* This is the only malloc call in this file */ +@@ -584,9 +590,11 @@ calculate_path(void) + else + buf[0] = '\0'; + ++#ifdef WITH_ZIP_PATH + /* Next is the default zip path */ + strcat(buf, zip_path); + strcat(buf, delimiter); ++#endif + + /* Next goes merge of compile-time $PYTHONPATH with + * dynamically located prefix. --- python2.7-2.7.15.orig/debian/patches/plat-gnukfreebsd.diff +++ python2.7-2.7.15/debian/patches/plat-gnukfreebsd.diff @@ -0,0 +1,2478 @@ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd7/IN.py +@@ -0,0 +1,809 @@ ++# Generated by h2py from /usr/include/netinet/in.h ++_NETINET_IN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from stdint.h ++_STDINT_H = 1 ++ ++# Included from bits/wchar.h ++_BITS_WCHAR_H = 1 ++__WCHAR_MAX = (2147483647) ++__WCHAR_MIN = (-__WCHAR_MAX - 1) ++def __INT64_C(c): return c ## L ++ ++def __UINT64_C(c): return c ## UL ++ ++def __INT64_C(c): return c ## LL ++ ++def __UINT64_C(c): return c ## ULL ++ ++INT8_MIN = (-128) ++INT16_MIN = (-32767-1) ++INT32_MIN = (-2147483647-1) ++INT64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT8_MAX = (127) ++INT16_MAX = (32767) ++INT32_MAX = (2147483647) ++INT64_MAX = (__INT64_C(9223372036854775807)) ++UINT8_MAX = (255) ++UINT16_MAX = (65535) ++UINT64_MAX = (__UINT64_C(18446744073709551615)) ++INT_LEAST8_MIN = (-128) ++INT_LEAST16_MIN = (-32767-1) ++INT_LEAST32_MIN = (-2147483647-1) ++INT_LEAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_LEAST8_MAX = (127) ++INT_LEAST16_MAX = (32767) ++INT_LEAST32_MAX = (2147483647) ++INT_LEAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_LEAST8_MAX = (255) ++UINT_LEAST16_MAX = (65535) ++UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) ++INT_FAST8_MIN = (-128) ++INT_FAST16_MIN = (-9223372036854775807L-1) ++INT_FAST32_MIN = (-9223372036854775807L-1) ++INT_FAST16_MIN = (-2147483647-1) ++INT_FAST32_MIN = (-2147483647-1) ++INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_FAST8_MAX = (127) ++INT_FAST16_MAX = (9223372036854775807L) ++INT_FAST32_MAX = (9223372036854775807L) ++INT_FAST16_MAX = (2147483647) ++INT_FAST32_MAX = (2147483647) ++INT_FAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_FAST8_MAX = (255) ++UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) ++INTPTR_MIN = (-9223372036854775807L-1) ++INTPTR_MAX = (9223372036854775807L) ++INTPTR_MIN = (-2147483647-1) ++INTPTR_MAX = (2147483647) ++INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) ++INTMAX_MAX = (__INT64_C(9223372036854775807)) ++UINTMAX_MAX = (__UINT64_C(18446744073709551615)) ++PTRDIFF_MIN = (-9223372036854775807L-1) ++PTRDIFF_MAX = (9223372036854775807L) ++PTRDIFF_MIN = (-2147483647-1) ++PTRDIFF_MAX = (2147483647) ++SIG_ATOMIC_MIN = (-2147483647-1) ++SIG_ATOMIC_MAX = (2147483647) ++WCHAR_MIN = __WCHAR_MIN ++WCHAR_MAX = __WCHAR_MAX ++def INT8_C(c): return c ++ ++def INT16_C(c): return c ++ ++def INT32_C(c): return c ++ ++def INT64_C(c): return c ## L ++ ++def INT64_C(c): return c ## LL ++ ++def UINT8_C(c): return c ++ ++def UINT16_C(c): return c ++ ++def UINT32_C(c): return c ## U ++ ++def UINT64_C(c): return c ## UL ++ ++def UINT64_C(c): return c ## ULL ++ ++def INTMAX_C(c): return c ## L ++ ++def UINTMAX_C(c): return c ## UL ++ ++def INTMAX_C(c): return c ## LL ++ ++def UINTMAX_C(c): return c ## ULL ++ ++ ++# Included from sys/socket.h ++_SYS_SOCKET_H = 1 ++ ++# Included from sys/uio.h ++_SYS_UIO_H = 1 ++from TYPES import * ++ ++# Included from bits/uio.h ++_BITS_UIO_H = 1 ++from TYPES import * ++UIO_MAXIOV = 1024 ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++ ++# Included from bits/socket.h ++__BITS_SOCKET_H = 1 ++ ++# Included from limits.h ++_LIBC_LIMITS_H_ = 1 ++MB_LEN_MAX = 16 ++_LIMITS_H = 1 ++CHAR_BIT = 8 ++SCHAR_MIN = (-128) ++SCHAR_MAX = 127 ++UCHAR_MAX = 255 ++CHAR_MIN = 0 ++CHAR_MAX = UCHAR_MAX ++CHAR_MIN = SCHAR_MIN ++CHAR_MAX = SCHAR_MAX ++SHRT_MIN = (-32768) ++SHRT_MAX = 32767 ++USHRT_MAX = 65535 ++INT_MAX = 2147483647 ++LONG_MAX = 9223372036854775807L ++LONG_MAX = 2147483647L ++LONG_MIN = (-LONG_MAX - 1L) ++ ++# Included from bits/posix1_lim.h ++_BITS_POSIX1_LIM_H = 1 ++_POSIX_AIO_LISTIO_MAX = 2 ++_POSIX_AIO_MAX = 1 ++_POSIX_ARG_MAX = 4096 ++_POSIX_CHILD_MAX = 25 ++_POSIX_CHILD_MAX = 6 ++_POSIX_DELAYTIMER_MAX = 32 ++_POSIX_HOST_NAME_MAX = 255 ++_POSIX_LINK_MAX = 8 ++_POSIX_LOGIN_NAME_MAX = 9 ++_POSIX_MAX_CANON = 255 ++_POSIX_MAX_INPUT = 255 ++_POSIX_MQ_OPEN_MAX = 8 ++_POSIX_MQ_PRIO_MAX = 32 ++_POSIX_NAME_MAX = 14 ++_POSIX_NGROUPS_MAX = 8 ++_POSIX_NGROUPS_MAX = 0 ++_POSIX_OPEN_MAX = 20 ++_POSIX_OPEN_MAX = 16 ++_POSIX_FD_SETSIZE = _POSIX_OPEN_MAX ++_POSIX_PATH_MAX = 256 ++_POSIX_PIPE_BUF = 512 ++_POSIX_RE_DUP_MAX = 255 ++_POSIX_RTSIG_MAX = 8 ++_POSIX_SEM_NSEMS_MAX = 256 ++_POSIX_SEM_VALUE_MAX = 32767 ++_POSIX_SIGQUEUE_MAX = 32 ++_POSIX_SSIZE_MAX = 32767 ++_POSIX_STREAM_MAX = 8 ++_POSIX_SYMLINK_MAX = 255 ++_POSIX_SYMLOOP_MAX = 8 ++_POSIX_TIMER_MAX = 32 ++_POSIX_TTY_NAME_MAX = 9 ++_POSIX_TZNAME_MAX = 6 ++_POSIX_QLIMIT = 1 ++_POSIX_HIWAT = _POSIX_PIPE_BUF ++_POSIX_UIO_MAXIOV = 16 ++_POSIX_CLOCKRES_MIN = 20000000 ++ ++# Included from bits/local_lim.h ++ ++# Included from sys/syslimits.h ++ARG_MAX = 262144 ++CHILD_MAX = 40 ++LINK_MAX = 32767 ++MAX_CANON = 255 ++MAX_INPUT = 255 ++NAME_MAX = 255 ++NGROUPS_MAX = 1023 ++OPEN_MAX = 64 ++PATH_MAX = 1024 ++PIPE_BUF = 512 ++IOV_MAX = 1024 ++_POSIX_THREAD_KEYS_MAX = 128 ++PTHREAD_KEYS_MAX = 1024 ++_POSIX_THREAD_DESTRUCTOR_ITERATIONS = 4 ++PTHREAD_DESTRUCTOR_ITERATIONS = _POSIX_THREAD_DESTRUCTOR_ITERATIONS ++_POSIX_THREAD_THREADS_MAX = 64 ++PTHREAD_THREADS_MAX = 1024 ++AIO_PRIO_DELTA_MAX = 20 ++PTHREAD_STACK_MIN = 16384 ++TIMER_MAX = 256 ++DELAYTIMER_MAX = 2147483647 ++SSIZE_MAX = LONG_MAX ++NGROUPS_MAX = 8 ++ ++# Included from bits/posix2_lim.h ++_BITS_POSIX2_LIM_H = 1 ++_POSIX2_BC_BASE_MAX = 99 ++_POSIX2_BC_DIM_MAX = 2048 ++_POSIX2_BC_SCALE_MAX = 99 ++_POSIX2_BC_STRING_MAX = 1000 ++_POSIX2_COLL_WEIGHTS_MAX = 2 ++_POSIX2_EXPR_NEST_MAX = 32 ++_POSIX2_LINE_MAX = 2048 ++_POSIX2_RE_DUP_MAX = 255 ++_POSIX2_CHARCLASS_NAME_MAX = 14 ++BC_BASE_MAX = _POSIX2_BC_BASE_MAX ++BC_DIM_MAX = _POSIX2_BC_DIM_MAX ++BC_SCALE_MAX = _POSIX2_BC_SCALE_MAX ++BC_STRING_MAX = _POSIX2_BC_STRING_MAX ++COLL_WEIGHTS_MAX = 255 ++EXPR_NEST_MAX = _POSIX2_EXPR_NEST_MAX ++LINE_MAX = _POSIX2_LINE_MAX ++CHARCLASS_NAME_MAX = 2048 ++RE_DUP_MAX = (0x7fff) ++ ++# Included from bits/xopen_lim.h ++_XOPEN_LIM_H = 1 ++ ++# Included from bits/stdio_lim.h ++L_tmpnam = 20 ++TMP_MAX = 238328 ++FILENAME_MAX = 1024 ++L_ctermid = 9 ++L_cuserid = 9 ++FOPEN_MAX = 64 ++IOV_MAX = 1024 ++_XOPEN_IOV_MAX = _POSIX_UIO_MAXIOV ++NL_ARGMAX = _POSIX_ARG_MAX ++NL_LANGMAX = _POSIX2_LINE_MAX ++NL_MSGMAX = INT_MAX ++NL_NMAX = INT_MAX ++NL_SETMAX = INT_MAX ++NL_TEXTMAX = INT_MAX ++NZERO = 20 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 32 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 64 ++LONG_BIT = 32 ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++PF_UNSPEC = 0 ++PF_LOCAL = 1 ++PF_UNIX = PF_LOCAL ++PF_FILE = PF_LOCAL ++PF_INET = 2 ++PF_IMPLINK = 3 ++PF_PUP = 4 ++PF_CHAOS = 5 ++PF_NS = 6 ++PF_ISO = 7 ++PF_OSI = PF_ISO ++PF_ECMA = 8 ++PF_DATAKIT = 9 ++PF_CCITT = 10 ++PF_SNA = 11 ++PF_DECnet = 12 ++PF_DLI = 13 ++PF_LAT = 14 ++PF_HYLINK = 15 ++PF_APPLETALK = 16 ++PF_ROUTE = 17 ++PF_LINK = 18 ++PF_XTP = 19 ++PF_COIP = 20 ++PF_CNT = 21 ++PF_RTIP = 22 ++PF_IPX = 23 ++PF_SIP = 24 ++PF_PIP = 25 ++PF_ISDN = 26 ++PF_KEY = 27 ++PF_INET6 = 28 ++PF_NATM = 29 ++PF_ATM = 30 ++PF_HDRCMPLT = 31 ++PF_NETGRAPH = 32 ++PF_MAX = 33 ++AF_UNSPEC = PF_UNSPEC ++AF_LOCAL = PF_LOCAL ++AF_UNIX = PF_UNIX ++AF_FILE = PF_FILE ++AF_INET = PF_INET ++AF_IMPLINK = PF_IMPLINK ++AF_PUP = PF_PUP ++AF_CHAOS = PF_CHAOS ++AF_NS = PF_NS ++AF_ISO = PF_ISO ++AF_OSI = PF_OSI ++AF_ECMA = PF_ECMA ++AF_DATAKIT = PF_DATAKIT ++AF_CCITT = PF_CCITT ++AF_SNA = PF_SNA ++AF_DECnet = PF_DECnet ++AF_DLI = PF_DLI ++AF_LAT = PF_LAT ++AF_HYLINK = PF_HYLINK ++AF_APPLETALK = PF_APPLETALK ++AF_ROUTE = PF_ROUTE ++AF_LINK = PF_LINK ++pseudo_AF_XTP = PF_XTP ++AF_COIP = PF_COIP ++AF_CNT = PF_CNT ++pseudo_AF_RTIP = PF_RTIP ++AF_IPX = PF_IPX ++AF_SIP = PF_SIP ++pseudo_AF_PIP = PF_PIP ++AF_ISDN = PF_ISDN ++AF_E164 = AF_ISDN ++pseudo_AF_KEY = PF_KEY ++AF_INET6 = PF_INET6 ++AF_NATM = PF_NATM ++AF_ATM = PF_ATM ++pseudo_AF_HDRCMPLT = PF_HDRCMPLT ++AF_NETGRAPH = PF_NETGRAPH ++AF_MAX = PF_MAX ++SOMAXCONN = 128 ++ ++# Included from bits/sockaddr.h ++_BITS_SOCKADDR_H = 1 ++def __SOCKADDR_COMMON(sa_prefix): return \ ++ ++_HAVE_SA_LEN = 1 ++_SS_SIZE = 128 ++def CMSG_FIRSTHDR(mhdr): return \ ++ ++CMGROUP_MAX = 16 ++SOL_SOCKET = 0xffff ++LOCAL_PEERCRED = 0x001 ++LOCAL_CREDS = 0x002 ++LOCAL_CONNWAIT = 0x004 ++ ++# Included from bits/socket2.h ++def IN_CLASSA(a): return ((((in_addr_t)(a)) & (-2147483648)) == 0) ++ ++IN_CLASSA_NET = (-16777216) ++IN_CLASSA_NSHIFT = 24 ++IN_CLASSA_HOST = ((-1) & ~IN_CLASSA_NET) ++IN_CLASSA_MAX = 128 ++def IN_CLASSB(a): return ((((in_addr_t)(a)) & (-1073741824)) == (-2147483648)) ++ ++IN_CLASSB_NET = (-65536) ++IN_CLASSB_NSHIFT = 16 ++IN_CLASSB_HOST = ((-1) & ~IN_CLASSB_NET) ++IN_CLASSB_MAX = 65536 ++def IN_CLASSC(a): return ((((in_addr_t)(a)) & (-536870912)) == (-1073741824)) ++ ++IN_CLASSC_NET = (-256) ++IN_CLASSC_NSHIFT = 8 ++IN_CLASSC_HOST = ((-1) & ~IN_CLASSC_NET) ++def IN_CLASSD(a): return ((((in_addr_t)(a)) & (-268435456)) == (-536870912)) ++ ++def IN_MULTICAST(a): return IN_CLASSD(a) ++ ++def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & (-536870912)) == (-536870912)) ++ ++def IN_BADCLASS(a): return ((((in_addr_t)(a)) & (-268435456)) == (-268435456)) ++ ++IN_LOOPBACKNET = 127 ++INET_ADDRSTRLEN = 16 ++INET6_ADDRSTRLEN = 46 ++ ++# Included from bits/in.h ++IMPLINK_IP = 155 ++IMPLINK_LOWEXPER = 156 ++IMPLINK_HIGHEXPER = 158 ++IPPROTO_DIVERT = 258 ++SOL_IP = 0 ++IP_OPTIONS = 1 ++IP_HDRINCL = 2 ++IP_TOS = 3 ++IP_TTL = 4 ++IP_RECVOPTS = 5 ++IP_RECVRETOPTS = 6 ++IP_RECVDSTADDR = 7 ++IP_SENDSRCADDR = IP_RECVDSTADDR ++IP_RETOPTS = 8 ++IP_MULTICAST_IF = 9 ++IP_MULTICAST_TTL = 10 ++IP_MULTICAST_LOOP = 11 ++IP_ADD_MEMBERSHIP = 12 ++IP_DROP_MEMBERSHIP = 13 ++IP_MULTICAST_VIF = 14 ++IP_RSVP_ON = 15 ++IP_RSVP_OFF = 16 ++IP_RSVP_VIF_ON = 17 ++IP_RSVP_VIF_OFF = 18 ++IP_PORTRANGE = 19 ++IP_RECVIF = 20 ++IP_IPSEC_POLICY = 21 ++IP_FAITH = 22 ++IP_ONESBCAST = 23 ++IP_NONLOCALOK = 24 ++IP_FW_TABLE_ADD = 40 ++IP_FW_TABLE_DEL = 41 ++IP_FW_TABLE_FLUSH = 42 ++IP_FW_TABLE_GETSIZE = 43 ++IP_FW_TABLE_LIST = 44 ++IP_FW_ADD = 50 ++IP_FW_DEL = 51 ++IP_FW_FLUSH = 52 ++IP_FW_ZERO = 53 ++IP_FW_GET = 54 ++IP_FW_RESETLOG = 55 ++IP_FW_NAT_CFG = 56 ++IP_FW_NAT_DEL = 57 ++IP_FW_NAT_GET_CONFIG = 58 ++IP_FW_NAT_GET_LOG = 59 ++IP_DUMMYNET_CONFIGURE = 60 ++IP_DUMMYNET_DEL = 61 ++IP_DUMMYNET_FLUSH = 62 ++IP_DUMMYNET_GET = 64 ++IP_RECVTTL = 65 ++IP_MINTTL = 66 ++IP_DONTFRAG = 67 ++IP_ADD_SOURCE_MEMBERSHIP = 70 ++IP_DROP_SOURCE_MEMBERSHIP = 71 ++IP_BLOCK_SOURCE = 72 ++IP_UNBLOCK_SOURCE = 73 ++IP_MSFILTER = 74 ++MCAST_JOIN_GROUP = 80 ++MCAST_LEAVE_GROUP = 81 ++MCAST_JOIN_SOURCE_GROUP = 82 ++MCAST_LEAVE_SOURCE_GROUP = 83 ++MCAST_BLOCK_SOURCE = 84 ++MCAST_UNBLOCK_SOURCE = 85 ++IP_DEFAULT_MULTICAST_TTL = 1 ++IP_DEFAULT_MULTICAST_LOOP = 1 ++IP_MIN_MEMBERSHIPS = 31 ++IP_MAX_MEMBERSHIPS = 4095 ++IP_MAX_SOURCE_FILTER = 1024 ++MCAST_UNDEFINED = 0 ++MCAST_INCLUDE = 1 ++MCAST_EXCLUDE = 2 ++IP_PORTRANGE_DEFAULT = 0 ++IP_PORTRANGE_HIGH = 1 ++IP_PORTRANGE_LOW = 2 ++IPCTL_FORWARDING = 1 ++IPCTL_SENDREDIRECTS = 2 ++IPCTL_DEFTTL = 3 ++IPCTL_DEFMTU = 4 ++IPCTL_RTEXPIRE = 5 ++IPCTL_RTMINEXPIRE = 6 ++IPCTL_RTMAXCACHE = 7 ++IPCTL_SOURCEROUTE = 8 ++IPCTL_DIRECTEDBROADCAST = 9 ++IPCTL_INTRQMAXLEN = 10 ++IPCTL_INTRQDROPS = 11 ++IPCTL_STATS = 12 ++IPCTL_ACCEPTSOURCEROUTE = 13 ++IPCTL_FASTFORWARDING = 14 ++IPCTL_KEEPFAITH = 15 ++IPCTL_GIF_TTL = 16 ++IPCTL_MAXID = 17 ++IPV6_SOCKOPT_RESERVED1 = 3 ++IPV6_UNICAST_HOPS = 4 ++IPV6_MULTICAST_IF = 9 ++IPV6_MULTICAST_HOPS = 10 ++IPV6_MULTICAST_LOOP = 11 ++IPV6_JOIN_GROUP = 12 ++IPV6_LEAVE_GROUP = 13 ++IPV6_PORTRANGE = 14 ++ICMP6_FILTER = 18 ++IPV6_CHECKSUM = 26 ++IPV6_V6ONLY = 27 ++IPV6_IPSEC_POLICY = 28 ++IPV6_FAITH = 29 ++IPV6_FW_ADD = 30 ++IPV6_FW_DEL = 31 ++IPV6_FW_FLUSH = 32 ++IPV6_FW_ZERO = 33 ++IPV6_FW_GET = 34 ++IPV6_RTHDRDSTOPTS = 35 ++IPV6_RECVPKTINFO = 36 ++IPV6_RECVHOPLIMIT = 37 ++IPV6_RECVRTHDR = 38 ++IPV6_RECVHOPOPTS = 39 ++IPV6_RECVDSTOPTS = 40 ++IPV6_USE_MIN_MTU = 42 ++IPV6_RECVPATHMTU = 43 ++IPV6_PATHMTU = 44 ++IPV6_PKTINFO = 46 ++IPV6_HOPLIMIT = 47 ++IPV6_NEXTHOP = 48 ++IPV6_HOPOPTS = 49 ++IPV6_DSTOPTS = 50 ++IPV6_RTHDR = 51 ++IPV6_RECVTCLASS = 57 ++IPV6_AUTOFLOWLABEL = 59 ++IPV6_TCLASS = 61 ++IPV6_DONTFRAG = 62 ++IPV6_PREFER_TEMPADDR = 63 ++IPV6_ADD_MEMBERSHIP = IPV6_JOIN_GROUP ++IPV6_DROP_MEMBERSHIP = IPV6_LEAVE_GROUP ++IPV6_RXHOPOPTS = IPV6_HOPOPTS ++IPV6_RXDSTOPTS = IPV6_DSTOPTS ++SOL_IPV6 = 41 ++SOL_ICMPV6 = 58 ++IPV6_DEFAULT_MULTICAST_HOPS = 1 ++IPV6_DEFAULT_MULTICAST_LOOP = 1 ++IPV6_PORTRANGE_DEFAULT = 0 ++IPV6_PORTRANGE_HIGH = 1 ++IPV6_PORTRANGE_LOW = 2 ++IPV6_RTHDR_LOOSE = 0 ++IPV6_RTHDR_STRICT = 1 ++IPV6_RTHDR_TYPE_0 = 0 ++IPV6CTL_FORWARDING = 1 ++IPV6CTL_SENDREDIRECTS = 2 ++IPV6CTL_DEFHLIM = 3 ++IPV6CTL_FORWSRCRT = 5 ++IPV6CTL_STATS = 6 ++IPV6CTL_MRTSTATS = 7 ++IPV6CTL_MRTPROTO = 8 ++IPV6CTL_MAXFRAGPACKETS = 9 ++IPV6CTL_SOURCECHECK = 10 ++IPV6CTL_SOURCECHECK_LOGINT = 11 ++IPV6CTL_ACCEPT_RTADV = 12 ++IPV6CTL_KEEPFAITH = 13 ++IPV6CTL_LOG_INTERVAL = 14 ++IPV6CTL_HDRNESTLIMIT = 15 ++IPV6CTL_DAD_COUNT = 16 ++IPV6CTL_AUTO_FLOWLABEL = 17 ++IPV6CTL_DEFMCASTHLIM = 18 ++IPV6CTL_GIF_HLIM = 19 ++IPV6CTL_KAME_VERSION = 20 ++IPV6CTL_USE_DEPRECATED = 21 ++IPV6CTL_RR_PRUNE = 22 ++IPV6CTL_V6ONLY = 24 ++IPV6CTL_RTEXPIRE = 25 ++IPV6CTL_RTMINEXPIRE = 26 ++IPV6CTL_RTMAXCACHE = 27 ++IPV6CTL_USETEMPADDR = 32 ++IPV6CTL_TEMPPLTIME = 33 ++IPV6CTL_TEMPVLTIME = 34 ++IPV6CTL_AUTO_LINKLOCAL = 35 ++IPV6CTL_RIP6STATS = 36 ++IPV6CTL_PREFER_TEMPADDR = 37 ++IPV6CTL_ADDRCTLPOLICY = 38 ++IPV6CTL_USE_DEFAULTZONE = 39 ++IPV6CTL_MAXFRAGS = 41 ++IPV6CTL_MCAST_PMTU = 44 ++IPV6CTL_STEALTH = 45 ++ICMPV6CTL_ND6_ONLINKNSRFC4861 = 47 ++IPV6CTL_MAXID = 48 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++def ntohl(x): return (x) ++ ++def ntohs(x): return (x) ++ ++def htonl(x): return (x) ++ ++def htons(x): return (x) ++ ++def ntohl(x): return __bswap_32 (x) ++ ++def ntohs(x): return __bswap_16 (x) ++ ++def htonl(x): return __bswap_32 (x) ++ ++def htons(x): return __bswap_16 (x) ++ ++def IN6_IS_ADDR_UNSPECIFIED(a): return \ ++ ++def IN6_IS_ADDR_LOOPBACK(a): return \ ++ ++def IN6_IS_ADDR_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_V4MAPPED(a): return \ ++ ++def IN6_IS_ADDR_V4COMPAT(a): return \ ++ ++def IN6_IS_ADDR_MC_NODELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_ORGLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_GLOBAL(a): return \ ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd7/TYPES.py +@@ -0,0 +1,303 @@ ++# Generated by h2py from /usr/include/sys/types.h ++_SYS_TYPES_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++ ++# Included from time.h ++_TIME_H = 1 ++ ++# Included from bits/time.h ++_BITS_TIME_H = 1 ++CLOCKS_PER_SEC = 1000000l ++CLK_TCK = 128 ++CLOCK_REALTIME = 0 ++CLOCK_PROCESS_CPUTIME_ID = 2 ++CLOCK_THREAD_CPUTIME_ID = 3 ++CLOCK_MONOTONIC = 4 ++CLOCK_VIRTUAL = 1 ++CLOCK_PROF = 2 ++CLOCK_UPTIME = 5 ++CLOCK_UPTIME_PRECISE = 7 ++CLOCK_UPTIME_FAST = 8 ++CLOCK_REALTIME_PRECISE = 9 ++CLOCK_REALTIME_FAST = 10 ++CLOCK_MONOTONIC_PRECISE = 11 ++CLOCK_MONOTONIC_FAST = 12 ++CLOCK_SECOND = 13 ++TIMER_RELTIME = 0 ++TIMER_ABSTIME = 1 ++_STRUCT_TIMEVAL = 1 ++CLK_TCK = CLOCKS_PER_SEC ++__clock_t_defined = 1 ++__time_t_defined = 1 ++__clockid_t_defined = 1 ++__timer_t_defined = 1 ++__timespec_defined = 1 ++ ++# Included from xlocale.h ++_XLOCALE_H = 1 ++def __isleap(year): return \ ++ ++__BIT_TYPES_DEFINED__ = 1 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++ ++# Included from sys/select.h ++_SYS_SELECT_H = 1 ++ ++# Included from bits/select.h ++def __FD_ZERO(fdsp): return \ ++ ++def __FD_ZERO(set): return \ ++ ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++def __FDELT(d): return ((d) / __NFDBITS) ++ ++FD_SETSIZE = __FD_SETSIZE ++def FD_ZERO(fdsetp): return __FD_ZERO (fdsetp) ++ ++ ++# Included from sys/sysmacros.h ++_SYS_SYSMACROS_H = 1 ++def minor(dev): return ((int)((dev) & (-65281))) ++ ++def gnu_dev_major(dev): return major (dev) ++ ++def gnu_dev_minor(dev): return minor (dev) ++ ++ ++# Included from bits/pthreadtypes.h ++_BITS_PTHREADTYPES_H = 1 ++ ++# Included from bits/sched.h ++SCHED_OTHER = 2 ++SCHED_FIFO = 1 ++SCHED_RR = 3 ++CSIGNAL = 0x000000ff ++CLONE_VM = 0x00000100 ++CLONE_FS = 0x00000200 ++CLONE_FILES = 0x00000400 ++CLONE_SIGHAND = 0x00000800 ++CLONE_PTRACE = 0x00002000 ++CLONE_VFORK = 0x00004000 ++CLONE_SYSVSEM = 0x00040000 ++__defined_schedparam = 1 ++__CPU_SETSIZE = 128 ++def __CPUELT(cpu): return ((cpu) / __NCPUBITS) ++ ++def __CPU_ALLOC_SIZE(count): return \ ++ ++def __CPU_ALLOC(count): return __sched_cpualloc (count) ++ ++def __CPU_FREE(cpuset): return __sched_cpufree (cpuset) ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd7/DLFCN.py +@@ -0,0 +1,118 @@ ++# Generated by h2py from /usr/include/dlfcn.h ++_DLFCN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/dlfcn.h ++RTLD_LAZY = 0x00001 ++RTLD_NOW = 0x00002 ++RTLD_BINDING_MASK = 0x3 ++RTLD_NOLOAD = 0x00004 ++RTLD_DEEPBIND = 0x00008 ++RTLD_GLOBAL = 0x00100 ++RTLD_LOCAL = 0 ++RTLD_NODELETE = 0x01000 ++LM_ID_BASE = 0 ++LM_ID_NEWLM = -1 +--- /dev/null ++++ b/Lib/plat-gnukfreebsd8/IN.py +@@ -0,0 +1,809 @@ ++# Generated by h2py from /usr/include/netinet/in.h ++_NETINET_IN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from stdint.h ++_STDINT_H = 1 ++ ++# Included from bits/wchar.h ++_BITS_WCHAR_H = 1 ++__WCHAR_MAX = (2147483647) ++__WCHAR_MIN = (-__WCHAR_MAX - 1) ++def __INT64_C(c): return c ## L ++ ++def __UINT64_C(c): return c ## UL ++ ++def __INT64_C(c): return c ## LL ++ ++def __UINT64_C(c): return c ## ULL ++ ++INT8_MIN = (-128) ++INT16_MIN = (-32767-1) ++INT32_MIN = (-2147483647-1) ++INT64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT8_MAX = (127) ++INT16_MAX = (32767) ++INT32_MAX = (2147483647) ++INT64_MAX = (__INT64_C(9223372036854775807)) ++UINT8_MAX = (255) ++UINT16_MAX = (65535) ++UINT64_MAX = (__UINT64_C(18446744073709551615)) ++INT_LEAST8_MIN = (-128) ++INT_LEAST16_MIN = (-32767-1) ++INT_LEAST32_MIN = (-2147483647-1) ++INT_LEAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_LEAST8_MAX = (127) ++INT_LEAST16_MAX = (32767) ++INT_LEAST32_MAX = (2147483647) ++INT_LEAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_LEAST8_MAX = (255) ++UINT_LEAST16_MAX = (65535) ++UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) ++INT_FAST8_MIN = (-128) ++INT_FAST16_MIN = (-9223372036854775807L-1) ++INT_FAST32_MIN = (-9223372036854775807L-1) ++INT_FAST16_MIN = (-2147483647-1) ++INT_FAST32_MIN = (-2147483647-1) ++INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_FAST8_MAX = (127) ++INT_FAST16_MAX = (9223372036854775807L) ++INT_FAST32_MAX = (9223372036854775807L) ++INT_FAST16_MAX = (2147483647) ++INT_FAST32_MAX = (2147483647) ++INT_FAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_FAST8_MAX = (255) ++UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) ++INTPTR_MIN = (-9223372036854775807L-1) ++INTPTR_MAX = (9223372036854775807L) ++INTPTR_MIN = (-2147483647-1) ++INTPTR_MAX = (2147483647) ++INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) ++INTMAX_MAX = (__INT64_C(9223372036854775807)) ++UINTMAX_MAX = (__UINT64_C(18446744073709551615)) ++PTRDIFF_MIN = (-9223372036854775807L-1) ++PTRDIFF_MAX = (9223372036854775807L) ++PTRDIFF_MIN = (-2147483647-1) ++PTRDIFF_MAX = (2147483647) ++SIG_ATOMIC_MIN = (-2147483647-1) ++SIG_ATOMIC_MAX = (2147483647) ++WCHAR_MIN = __WCHAR_MIN ++WCHAR_MAX = __WCHAR_MAX ++def INT8_C(c): return c ++ ++def INT16_C(c): return c ++ ++def INT32_C(c): return c ++ ++def INT64_C(c): return c ## L ++ ++def INT64_C(c): return c ## LL ++ ++def UINT8_C(c): return c ++ ++def UINT16_C(c): return c ++ ++def UINT32_C(c): return c ## U ++ ++def UINT64_C(c): return c ## UL ++ ++def UINT64_C(c): return c ## ULL ++ ++def INTMAX_C(c): return c ## L ++ ++def UINTMAX_C(c): return c ## UL ++ ++def INTMAX_C(c): return c ## LL ++ ++def UINTMAX_C(c): return c ## ULL ++ ++ ++# Included from sys/socket.h ++_SYS_SOCKET_H = 1 ++ ++# Included from sys/uio.h ++_SYS_UIO_H = 1 ++from TYPES import * ++ ++# Included from bits/uio.h ++_BITS_UIO_H = 1 ++from TYPES import * ++UIO_MAXIOV = 1024 ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++ ++# Included from bits/socket.h ++__BITS_SOCKET_H = 1 ++ ++# Included from limits.h ++_LIBC_LIMITS_H_ = 1 ++MB_LEN_MAX = 16 ++_LIMITS_H = 1 ++CHAR_BIT = 8 ++SCHAR_MIN = (-128) ++SCHAR_MAX = 127 ++UCHAR_MAX = 255 ++CHAR_MIN = 0 ++CHAR_MAX = UCHAR_MAX ++CHAR_MIN = SCHAR_MIN ++CHAR_MAX = SCHAR_MAX ++SHRT_MIN = (-32768) ++SHRT_MAX = 32767 ++USHRT_MAX = 65535 ++INT_MAX = 2147483647 ++LONG_MAX = 9223372036854775807L ++LONG_MAX = 2147483647L ++LONG_MIN = (-LONG_MAX - 1L) ++ ++# Included from bits/posix1_lim.h ++_BITS_POSIX1_LIM_H = 1 ++_POSIX_AIO_LISTIO_MAX = 2 ++_POSIX_AIO_MAX = 1 ++_POSIX_ARG_MAX = 4096 ++_POSIX_CHILD_MAX = 25 ++_POSIX_CHILD_MAX = 6 ++_POSIX_DELAYTIMER_MAX = 32 ++_POSIX_HOST_NAME_MAX = 255 ++_POSIX_LINK_MAX = 8 ++_POSIX_LOGIN_NAME_MAX = 9 ++_POSIX_MAX_CANON = 255 ++_POSIX_MAX_INPUT = 255 ++_POSIX_MQ_OPEN_MAX = 8 ++_POSIX_MQ_PRIO_MAX = 32 ++_POSIX_NAME_MAX = 14 ++_POSIX_NGROUPS_MAX = 8 ++_POSIX_NGROUPS_MAX = 0 ++_POSIX_OPEN_MAX = 20 ++_POSIX_OPEN_MAX = 16 ++_POSIX_FD_SETSIZE = _POSIX_OPEN_MAX ++_POSIX_PATH_MAX = 256 ++_POSIX_PIPE_BUF = 512 ++_POSIX_RE_DUP_MAX = 255 ++_POSIX_RTSIG_MAX = 8 ++_POSIX_SEM_NSEMS_MAX = 256 ++_POSIX_SEM_VALUE_MAX = 32767 ++_POSIX_SIGQUEUE_MAX = 32 ++_POSIX_SSIZE_MAX = 32767 ++_POSIX_STREAM_MAX = 8 ++_POSIX_SYMLINK_MAX = 255 ++_POSIX_SYMLOOP_MAX = 8 ++_POSIX_TIMER_MAX = 32 ++_POSIX_TTY_NAME_MAX = 9 ++_POSIX_TZNAME_MAX = 6 ++_POSIX_QLIMIT = 1 ++_POSIX_HIWAT = _POSIX_PIPE_BUF ++_POSIX_UIO_MAXIOV = 16 ++_POSIX_CLOCKRES_MIN = 20000000 ++ ++# Included from bits/local_lim.h ++ ++# Included from sys/syslimits.h ++ARG_MAX = 262144 ++CHILD_MAX = 40 ++LINK_MAX = 32767 ++MAX_CANON = 255 ++MAX_INPUT = 255 ++NAME_MAX = 255 ++NGROUPS_MAX = 1023 ++OPEN_MAX = 64 ++PATH_MAX = 1024 ++PIPE_BUF = 512 ++IOV_MAX = 1024 ++_POSIX_THREAD_KEYS_MAX = 128 ++PTHREAD_KEYS_MAX = 1024 ++_POSIX_THREAD_DESTRUCTOR_ITERATIONS = 4 ++PTHREAD_DESTRUCTOR_ITERATIONS = _POSIX_THREAD_DESTRUCTOR_ITERATIONS ++_POSIX_THREAD_THREADS_MAX = 64 ++PTHREAD_THREADS_MAX = 1024 ++AIO_PRIO_DELTA_MAX = 20 ++PTHREAD_STACK_MIN = 16384 ++TIMER_MAX = 256 ++DELAYTIMER_MAX = 2147483647 ++SSIZE_MAX = LONG_MAX ++NGROUPS_MAX = 8 ++ ++# Included from bits/posix2_lim.h ++_BITS_POSIX2_LIM_H = 1 ++_POSIX2_BC_BASE_MAX = 99 ++_POSIX2_BC_DIM_MAX = 2048 ++_POSIX2_BC_SCALE_MAX = 99 ++_POSIX2_BC_STRING_MAX = 1000 ++_POSIX2_COLL_WEIGHTS_MAX = 2 ++_POSIX2_EXPR_NEST_MAX = 32 ++_POSIX2_LINE_MAX = 2048 ++_POSIX2_RE_DUP_MAX = 255 ++_POSIX2_CHARCLASS_NAME_MAX = 14 ++BC_BASE_MAX = _POSIX2_BC_BASE_MAX ++BC_DIM_MAX = _POSIX2_BC_DIM_MAX ++BC_SCALE_MAX = _POSIX2_BC_SCALE_MAX ++BC_STRING_MAX = _POSIX2_BC_STRING_MAX ++COLL_WEIGHTS_MAX = 255 ++EXPR_NEST_MAX = _POSIX2_EXPR_NEST_MAX ++LINE_MAX = _POSIX2_LINE_MAX ++CHARCLASS_NAME_MAX = 2048 ++RE_DUP_MAX = (0x7fff) ++ ++# Included from bits/xopen_lim.h ++_XOPEN_LIM_H = 1 ++ ++# Included from bits/stdio_lim.h ++L_tmpnam = 20 ++TMP_MAX = 238328 ++FILENAME_MAX = 1024 ++L_ctermid = 9 ++L_cuserid = 9 ++FOPEN_MAX = 64 ++IOV_MAX = 1024 ++_XOPEN_IOV_MAX = _POSIX_UIO_MAXIOV ++NL_ARGMAX = _POSIX_ARG_MAX ++NL_LANGMAX = _POSIX2_LINE_MAX ++NL_MSGMAX = INT_MAX ++NL_NMAX = INT_MAX ++NL_SETMAX = INT_MAX ++NL_TEXTMAX = INT_MAX ++NZERO = 20 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 32 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 64 ++LONG_BIT = 32 ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++PF_UNSPEC = 0 ++PF_LOCAL = 1 ++PF_UNIX = PF_LOCAL ++PF_FILE = PF_LOCAL ++PF_INET = 2 ++PF_IMPLINK = 3 ++PF_PUP = 4 ++PF_CHAOS = 5 ++PF_NS = 6 ++PF_ISO = 7 ++PF_OSI = PF_ISO ++PF_ECMA = 8 ++PF_DATAKIT = 9 ++PF_CCITT = 10 ++PF_SNA = 11 ++PF_DECnet = 12 ++PF_DLI = 13 ++PF_LAT = 14 ++PF_HYLINK = 15 ++PF_APPLETALK = 16 ++PF_ROUTE = 17 ++PF_LINK = 18 ++PF_XTP = 19 ++PF_COIP = 20 ++PF_CNT = 21 ++PF_RTIP = 22 ++PF_IPX = 23 ++PF_SIP = 24 ++PF_PIP = 25 ++PF_ISDN = 26 ++PF_KEY = 27 ++PF_INET6 = 28 ++PF_NATM = 29 ++PF_ATM = 30 ++PF_HDRCMPLT = 31 ++PF_NETGRAPH = 32 ++PF_MAX = 33 ++AF_UNSPEC = PF_UNSPEC ++AF_LOCAL = PF_LOCAL ++AF_UNIX = PF_UNIX ++AF_FILE = PF_FILE ++AF_INET = PF_INET ++AF_IMPLINK = PF_IMPLINK ++AF_PUP = PF_PUP ++AF_CHAOS = PF_CHAOS ++AF_NS = PF_NS ++AF_ISO = PF_ISO ++AF_OSI = PF_OSI ++AF_ECMA = PF_ECMA ++AF_DATAKIT = PF_DATAKIT ++AF_CCITT = PF_CCITT ++AF_SNA = PF_SNA ++AF_DECnet = PF_DECnet ++AF_DLI = PF_DLI ++AF_LAT = PF_LAT ++AF_HYLINK = PF_HYLINK ++AF_APPLETALK = PF_APPLETALK ++AF_ROUTE = PF_ROUTE ++AF_LINK = PF_LINK ++pseudo_AF_XTP = PF_XTP ++AF_COIP = PF_COIP ++AF_CNT = PF_CNT ++pseudo_AF_RTIP = PF_RTIP ++AF_IPX = PF_IPX ++AF_SIP = PF_SIP ++pseudo_AF_PIP = PF_PIP ++AF_ISDN = PF_ISDN ++AF_E164 = AF_ISDN ++pseudo_AF_KEY = PF_KEY ++AF_INET6 = PF_INET6 ++AF_NATM = PF_NATM ++AF_ATM = PF_ATM ++pseudo_AF_HDRCMPLT = PF_HDRCMPLT ++AF_NETGRAPH = PF_NETGRAPH ++AF_MAX = PF_MAX ++SOMAXCONN = 128 ++ ++# Included from bits/sockaddr.h ++_BITS_SOCKADDR_H = 1 ++def __SOCKADDR_COMMON(sa_prefix): return \ ++ ++_HAVE_SA_LEN = 1 ++_SS_SIZE = 128 ++def CMSG_FIRSTHDR(mhdr): return \ ++ ++CMGROUP_MAX = 16 ++SOL_SOCKET = 0xffff ++LOCAL_PEERCRED = 0x001 ++LOCAL_CREDS = 0x002 ++LOCAL_CONNWAIT = 0x004 ++ ++# Included from bits/socket2.h ++def IN_CLASSA(a): return ((((in_addr_t)(a)) & (-2147483648)) == 0) ++ ++IN_CLASSA_NET = (-16777216) ++IN_CLASSA_NSHIFT = 24 ++IN_CLASSA_HOST = ((-1) & ~IN_CLASSA_NET) ++IN_CLASSA_MAX = 128 ++def IN_CLASSB(a): return ((((in_addr_t)(a)) & (-1073741824)) == (-2147483648)) ++ ++IN_CLASSB_NET = (-65536) ++IN_CLASSB_NSHIFT = 16 ++IN_CLASSB_HOST = ((-1) & ~IN_CLASSB_NET) ++IN_CLASSB_MAX = 65536 ++def IN_CLASSC(a): return ((((in_addr_t)(a)) & (-536870912)) == (-1073741824)) ++ ++IN_CLASSC_NET = (-256) ++IN_CLASSC_NSHIFT = 8 ++IN_CLASSC_HOST = ((-1) & ~IN_CLASSC_NET) ++def IN_CLASSD(a): return ((((in_addr_t)(a)) & (-268435456)) == (-536870912)) ++ ++def IN_MULTICAST(a): return IN_CLASSD(a) ++ ++def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & (-536870912)) == (-536870912)) ++ ++def IN_BADCLASS(a): return ((((in_addr_t)(a)) & (-268435456)) == (-268435456)) ++ ++IN_LOOPBACKNET = 127 ++INET_ADDRSTRLEN = 16 ++INET6_ADDRSTRLEN = 46 ++ ++# Included from bits/in.h ++IMPLINK_IP = 155 ++IMPLINK_LOWEXPER = 156 ++IMPLINK_HIGHEXPER = 158 ++IPPROTO_DIVERT = 258 ++SOL_IP = 0 ++IP_OPTIONS = 1 ++IP_HDRINCL = 2 ++IP_TOS = 3 ++IP_TTL = 4 ++IP_RECVOPTS = 5 ++IP_RECVRETOPTS = 6 ++IP_RECVDSTADDR = 7 ++IP_SENDSRCADDR = IP_RECVDSTADDR ++IP_RETOPTS = 8 ++IP_MULTICAST_IF = 9 ++IP_MULTICAST_TTL = 10 ++IP_MULTICAST_LOOP = 11 ++IP_ADD_MEMBERSHIP = 12 ++IP_DROP_MEMBERSHIP = 13 ++IP_MULTICAST_VIF = 14 ++IP_RSVP_ON = 15 ++IP_RSVP_OFF = 16 ++IP_RSVP_VIF_ON = 17 ++IP_RSVP_VIF_OFF = 18 ++IP_PORTRANGE = 19 ++IP_RECVIF = 20 ++IP_IPSEC_POLICY = 21 ++IP_FAITH = 22 ++IP_ONESBCAST = 23 ++IP_NONLOCALOK = 24 ++IP_FW_TABLE_ADD = 40 ++IP_FW_TABLE_DEL = 41 ++IP_FW_TABLE_FLUSH = 42 ++IP_FW_TABLE_GETSIZE = 43 ++IP_FW_TABLE_LIST = 44 ++IP_FW_ADD = 50 ++IP_FW_DEL = 51 ++IP_FW_FLUSH = 52 ++IP_FW_ZERO = 53 ++IP_FW_GET = 54 ++IP_FW_RESETLOG = 55 ++IP_FW_NAT_CFG = 56 ++IP_FW_NAT_DEL = 57 ++IP_FW_NAT_GET_CONFIG = 58 ++IP_FW_NAT_GET_LOG = 59 ++IP_DUMMYNET_CONFIGURE = 60 ++IP_DUMMYNET_DEL = 61 ++IP_DUMMYNET_FLUSH = 62 ++IP_DUMMYNET_GET = 64 ++IP_RECVTTL = 65 ++IP_MINTTL = 66 ++IP_DONTFRAG = 67 ++IP_ADD_SOURCE_MEMBERSHIP = 70 ++IP_DROP_SOURCE_MEMBERSHIP = 71 ++IP_BLOCK_SOURCE = 72 ++IP_UNBLOCK_SOURCE = 73 ++IP_MSFILTER = 74 ++MCAST_JOIN_GROUP = 80 ++MCAST_LEAVE_GROUP = 81 ++MCAST_JOIN_SOURCE_GROUP = 82 ++MCAST_LEAVE_SOURCE_GROUP = 83 ++MCAST_BLOCK_SOURCE = 84 ++MCAST_UNBLOCK_SOURCE = 85 ++IP_DEFAULT_MULTICAST_TTL = 1 ++IP_DEFAULT_MULTICAST_LOOP = 1 ++IP_MIN_MEMBERSHIPS = 31 ++IP_MAX_MEMBERSHIPS = 4095 ++IP_MAX_SOURCE_FILTER = 1024 ++MCAST_UNDEFINED = 0 ++MCAST_INCLUDE = 1 ++MCAST_EXCLUDE = 2 ++IP_PORTRANGE_DEFAULT = 0 ++IP_PORTRANGE_HIGH = 1 ++IP_PORTRANGE_LOW = 2 ++IPCTL_FORWARDING = 1 ++IPCTL_SENDREDIRECTS = 2 ++IPCTL_DEFTTL = 3 ++IPCTL_DEFMTU = 4 ++IPCTL_RTEXPIRE = 5 ++IPCTL_RTMINEXPIRE = 6 ++IPCTL_RTMAXCACHE = 7 ++IPCTL_SOURCEROUTE = 8 ++IPCTL_DIRECTEDBROADCAST = 9 ++IPCTL_INTRQMAXLEN = 10 ++IPCTL_INTRQDROPS = 11 ++IPCTL_STATS = 12 ++IPCTL_ACCEPTSOURCEROUTE = 13 ++IPCTL_FASTFORWARDING = 14 ++IPCTL_KEEPFAITH = 15 ++IPCTL_GIF_TTL = 16 ++IPCTL_MAXID = 17 ++IPV6_SOCKOPT_RESERVED1 = 3 ++IPV6_UNICAST_HOPS = 4 ++IPV6_MULTICAST_IF = 9 ++IPV6_MULTICAST_HOPS = 10 ++IPV6_MULTICAST_LOOP = 11 ++IPV6_JOIN_GROUP = 12 ++IPV6_LEAVE_GROUP = 13 ++IPV6_PORTRANGE = 14 ++ICMP6_FILTER = 18 ++IPV6_CHECKSUM = 26 ++IPV6_V6ONLY = 27 ++IPV6_IPSEC_POLICY = 28 ++IPV6_FAITH = 29 ++IPV6_FW_ADD = 30 ++IPV6_FW_DEL = 31 ++IPV6_FW_FLUSH = 32 ++IPV6_FW_ZERO = 33 ++IPV6_FW_GET = 34 ++IPV6_RTHDRDSTOPTS = 35 ++IPV6_RECVPKTINFO = 36 ++IPV6_RECVHOPLIMIT = 37 ++IPV6_RECVRTHDR = 38 ++IPV6_RECVHOPOPTS = 39 ++IPV6_RECVDSTOPTS = 40 ++IPV6_USE_MIN_MTU = 42 ++IPV6_RECVPATHMTU = 43 ++IPV6_PATHMTU = 44 ++IPV6_PKTINFO = 46 ++IPV6_HOPLIMIT = 47 ++IPV6_NEXTHOP = 48 ++IPV6_HOPOPTS = 49 ++IPV6_DSTOPTS = 50 ++IPV6_RTHDR = 51 ++IPV6_RECVTCLASS = 57 ++IPV6_AUTOFLOWLABEL = 59 ++IPV6_TCLASS = 61 ++IPV6_DONTFRAG = 62 ++IPV6_PREFER_TEMPADDR = 63 ++IPV6_ADD_MEMBERSHIP = IPV6_JOIN_GROUP ++IPV6_DROP_MEMBERSHIP = IPV6_LEAVE_GROUP ++IPV6_RXHOPOPTS = IPV6_HOPOPTS ++IPV6_RXDSTOPTS = IPV6_DSTOPTS ++SOL_IPV6 = 41 ++SOL_ICMPV6 = 58 ++IPV6_DEFAULT_MULTICAST_HOPS = 1 ++IPV6_DEFAULT_MULTICAST_LOOP = 1 ++IPV6_PORTRANGE_DEFAULT = 0 ++IPV6_PORTRANGE_HIGH = 1 ++IPV6_PORTRANGE_LOW = 2 ++IPV6_RTHDR_LOOSE = 0 ++IPV6_RTHDR_STRICT = 1 ++IPV6_RTHDR_TYPE_0 = 0 ++IPV6CTL_FORWARDING = 1 ++IPV6CTL_SENDREDIRECTS = 2 ++IPV6CTL_DEFHLIM = 3 ++IPV6CTL_FORWSRCRT = 5 ++IPV6CTL_STATS = 6 ++IPV6CTL_MRTSTATS = 7 ++IPV6CTL_MRTPROTO = 8 ++IPV6CTL_MAXFRAGPACKETS = 9 ++IPV6CTL_SOURCECHECK = 10 ++IPV6CTL_SOURCECHECK_LOGINT = 11 ++IPV6CTL_ACCEPT_RTADV = 12 ++IPV6CTL_KEEPFAITH = 13 ++IPV6CTL_LOG_INTERVAL = 14 ++IPV6CTL_HDRNESTLIMIT = 15 ++IPV6CTL_DAD_COUNT = 16 ++IPV6CTL_AUTO_FLOWLABEL = 17 ++IPV6CTL_DEFMCASTHLIM = 18 ++IPV6CTL_GIF_HLIM = 19 ++IPV6CTL_KAME_VERSION = 20 ++IPV6CTL_USE_DEPRECATED = 21 ++IPV6CTL_RR_PRUNE = 22 ++IPV6CTL_V6ONLY = 24 ++IPV6CTL_RTEXPIRE = 25 ++IPV6CTL_RTMINEXPIRE = 26 ++IPV6CTL_RTMAXCACHE = 27 ++IPV6CTL_USETEMPADDR = 32 ++IPV6CTL_TEMPPLTIME = 33 ++IPV6CTL_TEMPVLTIME = 34 ++IPV6CTL_AUTO_LINKLOCAL = 35 ++IPV6CTL_RIP6STATS = 36 ++IPV6CTL_PREFER_TEMPADDR = 37 ++IPV6CTL_ADDRCTLPOLICY = 38 ++IPV6CTL_USE_DEFAULTZONE = 39 ++IPV6CTL_MAXFRAGS = 41 ++IPV6CTL_MCAST_PMTU = 44 ++IPV6CTL_STEALTH = 45 ++ICMPV6CTL_ND6_ONLINKNSRFC4861 = 47 ++IPV6CTL_MAXID = 48 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++def ntohl(x): return (x) ++ ++def ntohs(x): return (x) ++ ++def htonl(x): return (x) ++ ++def htons(x): return (x) ++ ++def ntohl(x): return __bswap_32 (x) ++ ++def ntohs(x): return __bswap_16 (x) ++ ++def htonl(x): return __bswap_32 (x) ++ ++def htons(x): return __bswap_16 (x) ++ ++def IN6_IS_ADDR_UNSPECIFIED(a): return \ ++ ++def IN6_IS_ADDR_LOOPBACK(a): return \ ++ ++def IN6_IS_ADDR_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_V4MAPPED(a): return \ ++ ++def IN6_IS_ADDR_V4COMPAT(a): return \ ++ ++def IN6_IS_ADDR_MC_NODELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_ORGLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_GLOBAL(a): return \ ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd8/TYPES.py +@@ -0,0 +1,303 @@ ++# Generated by h2py from /usr/include/sys/types.h ++_SYS_TYPES_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++ ++# Included from time.h ++_TIME_H = 1 ++ ++# Included from bits/time.h ++_BITS_TIME_H = 1 ++CLOCKS_PER_SEC = 1000000l ++CLK_TCK = 128 ++CLOCK_REALTIME = 0 ++CLOCK_PROCESS_CPUTIME_ID = 2 ++CLOCK_THREAD_CPUTIME_ID = 3 ++CLOCK_MONOTONIC = 4 ++CLOCK_VIRTUAL = 1 ++CLOCK_PROF = 2 ++CLOCK_UPTIME = 5 ++CLOCK_UPTIME_PRECISE = 7 ++CLOCK_UPTIME_FAST = 8 ++CLOCK_REALTIME_PRECISE = 9 ++CLOCK_REALTIME_FAST = 10 ++CLOCK_MONOTONIC_PRECISE = 11 ++CLOCK_MONOTONIC_FAST = 12 ++CLOCK_SECOND = 13 ++TIMER_RELTIME = 0 ++TIMER_ABSTIME = 1 ++_STRUCT_TIMEVAL = 1 ++CLK_TCK = CLOCKS_PER_SEC ++__clock_t_defined = 1 ++__time_t_defined = 1 ++__clockid_t_defined = 1 ++__timer_t_defined = 1 ++__timespec_defined = 1 ++ ++# Included from xlocale.h ++_XLOCALE_H = 1 ++def __isleap(year): return \ ++ ++__BIT_TYPES_DEFINED__ = 1 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++ ++# Included from sys/select.h ++_SYS_SELECT_H = 1 ++ ++# Included from bits/select.h ++def __FD_ZERO(fdsp): return \ ++ ++def __FD_ZERO(set): return \ ++ ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++def __FDELT(d): return ((d) / __NFDBITS) ++ ++FD_SETSIZE = __FD_SETSIZE ++def FD_ZERO(fdsetp): return __FD_ZERO (fdsetp) ++ ++ ++# Included from sys/sysmacros.h ++_SYS_SYSMACROS_H = 1 ++def minor(dev): return ((int)((dev) & (-65281))) ++ ++def gnu_dev_major(dev): return major (dev) ++ ++def gnu_dev_minor(dev): return minor (dev) ++ ++ ++# Included from bits/pthreadtypes.h ++_BITS_PTHREADTYPES_H = 1 ++ ++# Included from bits/sched.h ++SCHED_OTHER = 2 ++SCHED_FIFO = 1 ++SCHED_RR = 3 ++CSIGNAL = 0x000000ff ++CLONE_VM = 0x00000100 ++CLONE_FS = 0x00000200 ++CLONE_FILES = 0x00000400 ++CLONE_SIGHAND = 0x00000800 ++CLONE_PTRACE = 0x00002000 ++CLONE_VFORK = 0x00004000 ++CLONE_SYSVSEM = 0x00040000 ++__defined_schedparam = 1 ++__CPU_SETSIZE = 128 ++def __CPUELT(cpu): return ((cpu) / __NCPUBITS) ++ ++def __CPU_ALLOC_SIZE(count): return \ ++ ++def __CPU_ALLOC(count): return __sched_cpualloc (count) ++ ++def __CPU_FREE(cpuset): return __sched_cpufree (cpuset) ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd8/DLFCN.py +@@ -0,0 +1,118 @@ ++# Generated by h2py from /usr/include/dlfcn.h ++_DLFCN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/dlfcn.h ++RTLD_LAZY = 0x00001 ++RTLD_NOW = 0x00002 ++RTLD_BINDING_MASK = 0x3 ++RTLD_NOLOAD = 0x00004 ++RTLD_DEEPBIND = 0x00008 ++RTLD_GLOBAL = 0x00100 ++RTLD_LOCAL = 0 ++RTLD_NODELETE = 0x01000 ++LM_ID_BASE = 0 ++LM_ID_NEWLM = -1 --- python2.7-2.7.15.orig/debian/patches/plat-linux2_alpha.diff +++ python2.7-2.7.15/debian/patches/plat-linux2_alpha.diff @@ -0,0 +1,73 @@ +Index: Lib/plat-linux2/IN.py +=================================================================== +--- ./Lib/plat-linux2/IN.py (Revision 77754) ++++ ./Lib/plat-linux2/IN.py (Arbeitskopie) +@@ -436,43 +436,43 @@ + # Included from asm/socket.h + + # Included from asm/sockios.h +-FIOSETOWN = 0x8901 +-SIOCSPGRP = 0x8902 +-FIOGETOWN = 0x8903 +-SIOCGPGRP = 0x8904 +-SIOCATMARK = 0x8905 ++FIOSETOWN = 0x8004667c ++SIOCSPGRP = 0x80047308 ++FIOGETOWN = 0x4004667b ++SIOCGPGRP = 0x40047309 ++SIOCATMARK = 0x40047307 + SIOCGSTAMP = 0x8906 +-SOL_SOCKET = 1 +-SO_DEBUG = 1 +-SO_REUSEADDR = 2 +-SO_TYPE = 3 +-SO_ERROR = 4 +-SO_DONTROUTE = 5 +-SO_BROADCAST = 6 +-SO_SNDBUF = 7 +-SO_RCVBUF = 8 +-SO_KEEPALIVE = 9 +-SO_OOBINLINE = 10 ++SOL_SOCKET = 0xffff ++SO_DEBUG = 0x0001 ++SO_REUSEADDR = 0x0004 ++SO_TYPE = 0x1008 ++SO_ERROR = 0x1007 ++SO_DONTROUTE = 0x0010 ++SO_BROADCAST = 0x0020 ++SO_SNDBUF = 0x1001 ++SO_RCVBUF = 0x1002 ++SO_KEEPALIVE = 0x0008 ++SO_OOBINLINE = 0x0100 + SO_NO_CHECK = 11 + SO_PRIORITY = 12 +-SO_LINGER = 13 ++SO_LINGER = 0x0080 + SO_BSDCOMPAT = 14 + SO_PASSCRED = 16 + SO_PEERCRED = 17 +-SO_RCVLOWAT = 18 +-SO_SNDLOWAT = 19 +-SO_RCVTIMEO = 20 +-SO_SNDTIMEO = 21 +-SO_SECURITY_AUTHENTICATION = 22 +-SO_SECURITY_ENCRYPTION_TRANSPORT = 23 +-SO_SECURITY_ENCRYPTION_NETWORK = 24 ++SO_RCVLOWAT = 0x1010 ++SO_SNDLOWAT = 0x1011 ++SO_RCVTIMEO = 0x1012 ++SO_SNDTIMEO = 0x1013 ++SO_SECURITY_AUTHENTICATION = 19 ++SO_SECURITY_ENCRYPTION_TRANSPORT = 20 ++SO_SECURITY_ENCRYPTION_NETWORK = 21 + SO_BINDTODEVICE = 25 + SO_ATTACH_FILTER = 26 + SO_DETACH_FILTER = 27 + SO_PEERNAME = 28 + SO_TIMESTAMP = 29 + SCM_TIMESTAMP = SO_TIMESTAMP +-SO_ACCEPTCONN = 30 ++SO_ACCEPTCONN = 0x1014 + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 --- python2.7-2.7.15.orig/debian/patches/plat-linux2_hppa.diff +++ python2.7-2.7.15/debian/patches/plat-linux2_hppa.diff @@ -0,0 +1,72 @@ +Index: Lib/plat-linux2/IN.py +=================================================================== +--- ./Lib/plat-linux2/IN.py (Revision 77754) ++++ ./Lib/plat-linux2/IN.py (Arbeitskopie) +@@ -442,37 +442,37 @@ + SIOCGPGRP = 0x8904 + SIOCATMARK = 0x8905 + SIOCGSTAMP = 0x8906 +-SOL_SOCKET = 1 +-SO_DEBUG = 1 +-SO_REUSEADDR = 2 +-SO_TYPE = 3 +-SO_ERROR = 4 +-SO_DONTROUTE = 5 +-SO_BROADCAST = 6 +-SO_SNDBUF = 7 +-SO_RCVBUF = 8 +-SO_KEEPALIVE = 9 +-SO_OOBINLINE = 10 +-SO_NO_CHECK = 11 +-SO_PRIORITY = 12 +-SO_LINGER = 13 +-SO_BSDCOMPAT = 14 +-SO_PASSCRED = 16 +-SO_PEERCRED = 17 +-SO_RCVLOWAT = 18 +-SO_SNDLOWAT = 19 +-SO_RCVTIMEO = 20 +-SO_SNDTIMEO = 21 +-SO_SECURITY_AUTHENTICATION = 22 +-SO_SECURITY_ENCRYPTION_TRANSPORT = 23 +-SO_SECURITY_ENCRYPTION_NETWORK = 24 +-SO_BINDTODEVICE = 25 +-SO_ATTACH_FILTER = 26 +-SO_DETACH_FILTER = 27 +-SO_PEERNAME = 28 +-SO_TIMESTAMP = 29 ++SOL_SOCKET = 0xffff ++SO_DEBUG = 0x0001 ++SO_REUSEADDR = 0x0004 ++SO_TYPE = 0x1008 ++SO_ERROR = 0x1007 ++SO_DONTROUTE = 0x0010 ++SO_BROADCAST = 0x0020 ++SO_SNDBUF = 0x1001 ++SO_RCVBUF = 0x1002 ++SO_KEEPALIVE = 0x0008 ++SO_OOBINLINE = 0x0100 ++SO_NO_CHECK = 0x400b ++SO_PRIORITY = 0x400c ++SO_LINGER = 0x0080 ++SO_BSDCOMPAT = 0x400e ++SO_PASSCRED = 0x4010 ++SO_PEERCRED = 0x4011 ++SO_RCVLOWAT = 0x1004 ++SO_SNDLOWAT = 0x1003 ++SO_RCVTIMEO = 0x1006 ++SO_SNDTIMEO = 0x1005 ++SO_SECURITY_AUTHENTICATION = 0x4016 ++SO_SECURITY_ENCRYPTION_TRANSPORT = 0x4017 ++SO_SECURITY_ENCRYPTION_NETWORK = 0x4018 ++SO_BINDTODEVICE = 0x4019 ++SO_ATTACH_FILTER = 0x401a ++SO_DETACH_FILTER = 0x401b ++SO_PEERNAME = 0x2000 ++SO_TIMESTAMP = 0x4012 + SCM_TIMESTAMP = SO_TIMESTAMP +-SO_ACCEPTCONN = 30 ++SO_ACCEPTCONN = 0x401c + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 --- python2.7-2.7.15.orig/debian/patches/plat-linux2_mips.diff +++ python2.7-2.7.15/debian/patches/plat-linux2_mips.diff @@ -0,0 +1,88 @@ +Index: Lib/plat-linux2/DLFCN.py +=================================================================== +--- ./Lib/plat-linux2/DLFCN.py (Revision 77754) ++++ ./Lib/plat-linux2/DLFCN.py (Arbeitskopie) +@@ -77,7 +77,7 @@ + RTLD_LAZY = 0x00001 + RTLD_NOW = 0x00002 + RTLD_BINDING_MASK = 0x3 +-RTLD_NOLOAD = 0x00004 +-RTLD_GLOBAL = 0x00100 ++RTLD_NOLOAD = 0x00008 ++RTLD_GLOBAL = 0x00004 + RTLD_LOCAL = 0 + RTLD_NODELETE = 0x01000 +Index: Lib/plat-linux2/IN.py +=================================================================== +--- ./Lib/plat-linux2/IN.py (Revision 77754) ++++ ./Lib/plat-linux2/IN.py (Arbeitskopie) +@@ -436,33 +436,33 @@ + # Included from asm/socket.h + + # Included from asm/sockios.h +-FIOSETOWN = 0x8901 +-SIOCSPGRP = 0x8902 +-FIOGETOWN = 0x8903 +-SIOCGPGRP = 0x8904 +-SIOCATMARK = 0x8905 ++FIOSETOWN = 0x8004667c ++SIOCSPGRP = 0x80047308 ++FIOGETOWN = 0x4004667b ++SIOCGPGRP = 0x40047309 ++SIOCATMARK = 0x40047307 + SIOCGSTAMP = 0x8906 +-SOL_SOCKET = 1 +-SO_DEBUG = 1 +-SO_REUSEADDR = 2 +-SO_TYPE = 3 +-SO_ERROR = 4 +-SO_DONTROUTE = 5 +-SO_BROADCAST = 6 +-SO_SNDBUF = 7 +-SO_RCVBUF = 8 +-SO_KEEPALIVE = 9 +-SO_OOBINLINE = 10 ++SOL_SOCKET = 0xffff ++SO_DEBUG = 0x0001 ++SO_REUSEADDR = 0x0004 ++SO_TYPE = 0x1008 ++SO_ERROR = 0x1007 ++SO_DONTROUTE = 0x0010 ++SO_BROADCAST = 0x0020 ++SO_SNDBUF = 0x1001 ++SO_RCVBUF = 0x1002 ++SO_KEEPALIVE = 0x0008 ++SO_OOBINLINE = 0x0100 + SO_NO_CHECK = 11 + SO_PRIORITY = 12 +-SO_LINGER = 13 ++SO_LINGER = 0x0080 + SO_BSDCOMPAT = 14 +-SO_PASSCRED = 16 +-SO_PEERCRED = 17 +-SO_RCVLOWAT = 18 +-SO_SNDLOWAT = 19 +-SO_RCVTIMEO = 20 +-SO_SNDTIMEO = 21 ++SO_PASSCRED = 17 ++SO_PEERCRED = 18 ++SO_RCVLOWAT = 0x1004 ++SO_SNDLOWAT = 0x1003 ++SO_RCVTIMEO = 0x1006 ++SO_SNDTIMEO = 0x1005 + SO_SECURITY_AUTHENTICATION = 22 + SO_SECURITY_ENCRYPTION_TRANSPORT = 23 + SO_SECURITY_ENCRYPTION_NETWORK = 24 +@@ -472,9 +472,9 @@ + SO_PEERNAME = 28 + SO_TIMESTAMP = 29 + SCM_TIMESTAMP = SO_TIMESTAMP +-SO_ACCEPTCONN = 30 +-SOCK_STREAM = 1 +-SOCK_DGRAM = 2 ++SO_ACCEPTCONN = 0x1009 ++SOCK_STREAM = 2 ++SOCK_DGRAM = 1 + SOCK_RAW = 3 + SOCK_RDM = 4 + SOCK_SEQPACKET = 5 --- python2.7-2.7.15.orig/debian/patches/plat-linux2_sparc.diff +++ python2.7-2.7.15/debian/patches/plat-linux2_sparc.diff @@ -0,0 +1,72 @@ +Index: Lib/plat-linux2/IN.py +=================================================================== +--- ./Lib/plat-linux2/IN.py (Revision 77754) ++++ ./Lib/plat-linux2/IN.py (Arbeitskopie) +@@ -442,37 +442,37 @@ + SIOCGPGRP = 0x8904 + SIOCATMARK = 0x8905 + SIOCGSTAMP = 0x8906 +-SOL_SOCKET = 1 +-SO_DEBUG = 1 +-SO_REUSEADDR = 2 +-SO_TYPE = 3 +-SO_ERROR = 4 +-SO_DONTROUTE = 5 +-SO_BROADCAST = 6 +-SO_SNDBUF = 7 +-SO_RCVBUF = 8 +-SO_KEEPALIVE = 9 +-SO_OOBINLINE = 10 +-SO_NO_CHECK = 11 +-SO_PRIORITY = 12 +-SO_LINGER = 13 +-SO_BSDCOMPAT = 14 +-SO_PASSCRED = 16 +-SO_PEERCRED = 17 +-SO_RCVLOWAT = 18 +-SO_SNDLOWAT = 19 +-SO_RCVTIMEO = 20 +-SO_SNDTIMEO = 21 +-SO_SECURITY_AUTHENTICATION = 22 +-SO_SECURITY_ENCRYPTION_TRANSPORT = 23 +-SO_SECURITY_ENCRYPTION_NETWORK = 24 +-SO_BINDTODEVICE = 25 +-SO_ATTACH_FILTER = 26 +-SO_DETACH_FILTER = 27 +-SO_PEERNAME = 28 +-SO_TIMESTAMP = 29 ++SOL_SOCKET = 0xffff ++SO_DEBUG = 0x0001 ++SO_REUSEADDR = 0x0004 ++SO_TYPE = 0x1008 ++SO_ERROR = 0x1007 ++SO_DONTROUTE = 0x0010 ++SO_BROADCAST = 0x0020 ++SO_SNDBUF = 0x1001 ++SO_RCVBUF = 0x1002 ++SO_KEEPALIVE = 0x0008 ++SO_OOBINLINE = 0x0100 ++SO_NO_CHECK = 0x000b ++SO_PRIORITY = 0x000c ++SO_LINGER = 0x0080 ++SO_BSDCOMPAT = 0x0400 ++SO_PASSCRED = 0x0002 ++SO_PEERCRED = 0x0040 ++SO_RCVLOWAT = 0x0800 ++SO_SNDLOWAT = 0x1000 ++SO_RCVTIMEO = 0x2000 ++SO_SNDTIMEO = 0x4000 ++SO_SECURITY_AUTHENTICATION = 0x5001 ++SO_SECURITY_ENCRYPTION_TRANSPORT = 0x5002 ++SO_SECURITY_ENCRYPTION_NETWORK = 0x5004 ++SO_BINDTODEVICE = 0x000d ++SO_ATTACH_FILTER = 0x001a ++SO_DETACH_FILTER = 0x001b ++SO_PEERNAME = 0x001c ++SO_TIMESTAMP = 0x001d + SCM_TIMESTAMP = SO_TIMESTAMP +-SO_ACCEPTCONN = 30 ++SO_ACCEPTCONN = 0x8000 + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 --- python2.7-2.7.15.orig/debian/patches/platform-lsbrelease.diff +++ python2.7-2.7.15/debian/patches/platform-lsbrelease.diff @@ -0,0 +1,52 @@ +# DP: Use /etc/lsb-release to identify the platform. + +Index: b/Lib/platform.py +=================================================================== +--- a/Lib/platform.py ++++ b/Lib/platform.py +@@ -290,7 +290,7 @@ _release_version = re.compile(r'([^0-9]+ + _supported_dists = ( + 'SuSE', 'debian', 'fedora', 'redhat', 'centos', + 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo', +- 'UnitedLinux', 'turbolinux') ++ 'UnitedLinux', 'turbolinux', 'Ubuntu') + + def _parse_release_file(firstline): + +@@ -319,6 +319,10 @@ def _parse_release_file(firstline): + id = l[1] + return '', version, id + ++_distributor_id_file_re = re.compile("(?:DISTRIB_ID\s*=)\s*(.*)", re.I) ++_release_file_re = re.compile("(?:DISTRIB_RELEASE\s*=)\s*(.*)", re.I) ++_codename_file_re = re.compile("(?:DISTRIB_CODENAME\s*=)\s*(.*)", re.I) ++ + def linux_distribution(distname='', version='', id='', + + supported_dists=_supported_dists, +@@ -343,6 +347,25 @@ def linux_distribution(distname='', vers + args given as parameters. + + """ ++ # check for the LSB /etc/lsb-release file first, needed so ++ # that the distribution doesn't get identified as Debian. ++ try: ++ with open("/etc/lsb-release", "rU") as etclsbrel: ++ for line in etclsbrel: ++ m = _distributor_id_file_re.search(line) ++ if m: ++ _u_distname = m.group(1).strip() ++ m = _release_file_re.search(line) ++ if m: ++ _u_version = m.group(1).strip() ++ m = _codename_file_re.search(line) ++ if m: ++ _u_id = m.group(1).strip() ++ if _u_distname and _u_version: ++ return (_u_distname, _u_version, _u_id) ++ except (EnvironmentError, UnboundLocalError): ++ pass ++ + try: + etc = os.listdir('/etc') + except os.error: --- python2.7-2.7.15.orig/debian/patches/pydoc-use-pager.diff +++ python2.7-2.7.15/debian/patches/pydoc-use-pager.diff @@ -0,0 +1,15 @@ +# DP: pydoc: use the pager command if available. + +Index: b/Lib/pydoc.py +=================================================================== +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -1395,6 +1395,8 @@ def getpager(): + 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('(pager) 2>/dev/null') == 0: ++ return lambda text: pipepager(text, 'pager') + if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: + return lambda text: pipepager(text, 'less') + --- python2.7-2.7.15.orig/debian/patches/rename-md5-init.diff +++ python2.7-2.7.15/debian/patches/rename-md5-init.diff @@ -0,0 +1,124 @@ +Index: b/Modules/md5.c +=================================================================== +--- a/Modules/md5.c ++++ b/Modules/md5.c +@@ -311,7 +311,7 @@ md5_process(md5_state_t *pms, const md5_ + } + + void +-md5_init(md5_state_t *pms) ++_Py_md5_init(md5_state_t *pms) + { + pms->count[0] = pms->count[1] = 0; + pms->abcd[0] = 0x67452301; +@@ -321,7 +321,7 @@ md5_init(md5_state_t *pms) + } + + void +-md5_append(md5_state_t *pms, const md5_byte_t *data, unsigned int nbytes) ++_Py_md5_append(md5_state_t *pms, const md5_byte_t *data, unsigned int nbytes) + { + const md5_byte_t *p = data; + unsigned int left = nbytes; +@@ -338,8 +338,8 @@ md5_append(md5_state_t *pms, const md5_b + /* handle the append in two steps to prevent overflow */ + overlap = 64 - offset; + +- md5_append(pms, data, overlap); +- md5_append(pms, data + overlap, nbytes - overlap); ++ _Py_md5_append(pms, data, overlap); ++ _Py_md5_append(pms, data + overlap, nbytes - overlap); + return; + } + +@@ -371,7 +371,7 @@ md5_append(md5_state_t *pms, const md5_b + } + + void +-md5_finish(md5_state_t *pms, md5_byte_t digest[16]) ++_Py_md5_finish(md5_state_t *pms, md5_byte_t digest[16]) + { + static const md5_byte_t pad[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +@@ -386,9 +386,9 @@ md5_finish(md5_state_t *pms, md5_byte_t + for (i = 0; i < 8; ++i) + data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); + /* Pad to 56 bytes mod 64. */ +- md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); ++ _Py_md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); + /* Append the length. */ +- md5_append(pms, data, 8); ++ _Py_md5_append(pms, data, 8); + for (i = 0; i < 16; ++i) + digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); + } +Index: b/Modules/md5.h +=================================================================== +--- a/Modules/md5.h ++++ b/Modules/md5.h +@@ -76,13 +76,13 @@ extern "C" + #endif + + /* Initialize the algorithm. */ +-void md5_init(md5_state_t *pms); ++void _Py_md5_init(md5_state_t *pms); + + /* Append a string to the message. */ +-void md5_append(md5_state_t *pms, const md5_byte_t *data, unsigned int nbytes); ++void _Py_md5_append(md5_state_t *pms, const md5_byte_t *data, unsigned int nbytes); + + /* Finish the message and return the digest. */ +-void md5_finish(md5_state_t *pms, md5_byte_t digest[16]); ++void _Py_md5_finish(md5_state_t *pms, md5_byte_t digest[16]); + + #ifdef __cplusplus + } /* end extern "C" */ +Index: b/Modules/md5module.c +=================================================================== +--- a/Modules/md5module.c ++++ b/Modules/md5module.c +@@ -31,7 +31,7 @@ newmd5object(void) + if (md5p == NULL) + return NULL; + +- md5_init(&md5p->md5); /* actual initialisation */ ++ _Py_md5_init(&md5p->md5); /* actual initialisation */ + return md5p; + } + +@@ -65,7 +65,7 @@ md5_update(md5object *self, PyObject *ar + nbytes = INT_MAX; + else + nbytes = n; +- md5_append(&self->md5, buf, ++ _Py_md5_append(&self->md5, buf, + Py_SAFE_DOWNCAST(nbytes, Py_ssize_t, unsigned int)); + buf += nbytes; + n -= nbytes; +@@ -91,7 +91,7 @@ md5_digest(md5object *self) + + /* make a temporary copy, and perform the final */ + mdContext = self->md5; +- md5_finish(&mdContext, aDigest); ++ _Py_md5_finish(&mdContext, aDigest); + + return PyString_FromStringAndSize((char *)aDigest, 16); + } +@@ -114,7 +114,7 @@ md5_hexdigest(md5object *self) + + /* make a temporary copy, and perform the final */ + mdContext = self->md5; +- md5_finish(&mdContext, digest); ++ _Py_md5_finish(&mdContext, digest); + + /* Make hex version of the digest */ + for(i=j=0; i<16; i++) { +@@ -294,7 +294,7 @@ MD5_new(PyObject *self, PyObject *args) + nbytes = INT_MAX; + else + nbytes = n; +- md5_append(&md5p->md5, buf, ++ _Py_md5_append(&md5p->md5, buf, + Py_SAFE_DOWNCAST(nbytes, Py_ssize_t, unsigned int)); + buf += nbytes; + n -= nbytes; --- python2.7-2.7.15.orig/debian/patches/reproducible-buildinfo.diff +++ python2.7-2.7.15/debian/patches/reproducible-buildinfo.diff @@ -0,0 +1,15 @@ +# DP: Build getbuildinfo.o with DATE/TIME values when defined + +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -660,6 +660,8 @@ Modules/getbuildinfo.o: $(PARSER_OBJS) \ + -DGITVERSION="\"`LC_ALL=C $(GITVERSION)`\"" \ + -DGITTAG="\"`LC_ALL=C $(GITTAG)`\"" \ + -DGITBRANCH="\"`LC_ALL=C $(GITBRANCH)`\"" \ ++ $(if $(BUILD_DATE),-DDATE='"$(BUILD_DATE)"') \ ++ $(if $(BUILD_TIME),-DTIME='"$(BUILD_TIME)"') \ + -o $@ $(srcdir)/Modules/getbuildinfo.c + + Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile --- python2.7-2.7.15.orig/debian/patches/revert-unittest-loader-symlinks19352.diff +++ python2.7-2.7.15/debian/patches/revert-unittest-loader-symlinks19352.diff @@ -0,0 +1,68 @@ +Description: DP: Revert patch from http://bugs.python.org/issue19352 as it completely breaks unittest discovery on Debian/Ubuntu +Bug-Ubuntu: https://launchpad.net/bugs/1255505 + +Index: b/Lib/unittest/loader.py +=================================================================== +--- a/Lib/unittest/loader.py ++++ b/Lib/unittest/loader.py +@@ -256,8 +256,8 @@ class TestLoader(object): + yield _make_failed_import_test(name, self.suiteClass) + else: + mod_file = os.path.abspath(getattr(module, '__file__', full_path)) +- realpath = os.path.splitext(os.path.realpath(mod_file))[0] +- fullpath_noext = os.path.splitext(os.path.realpath(full_path))[0] ++ realpath = os.path.splitext(mod_file)[0] ++ fullpath_noext = os.path.splitext(full_path)[0] + if realpath.lower() != fullpath_noext.lower(): + module_dir = os.path.dirname(realpath) + mod_name = os.path.splitext(os.path.basename(full_path))[0] +Index: b/Lib/unittest/test/test_discovery.py +=================================================================== +--- a/Lib/unittest/test/test_discovery.py ++++ b/Lib/unittest/test/test_discovery.py +@@ -315,7 +315,7 @@ class TestDiscovery(unittest.TestCase): + self.assertTrue(program.failfast) + self.assertTrue(program.catchbreak) + +- def setup_module_clash(self): ++ def test_detect_module_clash(self): + class Module(object): + __file__ = 'bar/foo.py' + sys.modules['foo'] = Module +@@ -342,10 +342,7 @@ class TestDiscovery(unittest.TestCase): + os.listdir = listdir + os.path.isfile = isfile + os.path.isdir = isdir +- return full_path + +- def test_detect_module_clash(self): +- full_path = self.setup_module_clash() + loader = unittest.TestLoader() + + mod_dir = os.path.abspath('bar') +@@ -358,25 +355,6 @@ class TestDiscovery(unittest.TestCase): + ) + self.assertEqual(sys.path[0], full_path) + +- def test_module_symlink_ok(self): +- full_path = self.setup_module_clash() +- +- original_realpath = os.path.realpath +- +- mod_dir = os.path.abspath('bar') +- expected_dir = os.path.abspath('foo') +- +- def cleanup(): +- os.path.realpath = original_realpath +- self.addCleanup(cleanup) +- +- def realpath(path): +- if path == os.path.join(mod_dir, 'foo.py'): +- return os.path.join(expected_dir, 'foo.py') +- return path +- os.path.realpath = realpath +- loader = unittest.TestLoader() +- loader.discover(start_dir='foo', pattern='foo.py') + + def test_discovery_from_dotted_path(self): + loader = unittest.TestLoader() --- python2.7-2.7.15.orig/debian/patches/series.in +++ python2.7-2.7.15/debian/patches/series.in @@ -0,0 +1,76 @@ +git-updates.diff +issue9189.diff +build-libpython.diff +deb-setup.diff +deb-locations.diff +site-locations.diff +distutils-install-layout.diff +locale-module.diff +distutils-link.diff +distutils-sysconfig.diff +test-sundry.diff +tkinter-import.diff +link-opt.diff +debug-build.diff +hotshot-import.diff +no-zip-on-sys.path.diff +platform-lsbrelease.diff +bdist-wininst-notfound.diff +setup-modules-ssl.diff +makesetup-bashism.diff +hurd-disable-nonworking-constants.diff +#ifdef WITH_FPECTL +enable-fpectl.diff +#endif +statvfs-f_flag-constants.diff +#if defined (arch_alpha) +plat-linux2_alpha.diff +#elif defined (arch_hppa) +plat-linux2_hppa.diff +#elif defined (arch_mips) || defined(arch_mipsel) || defined(arch_mipsn32) || defined(arch_mipsn32el) || defined (arch_mips64) || defined(arch_mips64el) \ + || defined(arch_mipsr6) || defined(arch_mipsr6el) || defined(arch_mipsn32r6) || defined(arch_mipsn32r6el) || defined(arch_mips64r6) || defined(arch_mips64r6el) +plat-linux2_mips.diff +#elif defined (arch_sparc) || defined (arch_sparc64) +plat-linux2_sparc.diff +#endif +#if defined (BROKEN_UTIMES) +disable-utimes.diff +#endif +#if defined (Ubuntu) +langpack-gettext.diff +#endif +#if defined (arch_os_hurd) +no-large-file-support.diff +cthreads.diff +#endif +issue9012a.diff +link-system-expat.diff +plat-gnukfreebsd.diff +link-whole-archive.diff +bsddb-libpath.diff +disable-sem-check.diff +ctypes-arm.diff +lto-link-flags.diff +multiarch.diff +lib2to3-no-pickled-grammar.diff +add-python-config-sh.diff +ext-no-libpython-link.diff +build-hash.diff +libffi-shared.diff +atomic-pyc-rename.diff +revert-unittest-loader-symlinks19352.diff +enable-sqlite-loadext.diff +installed-testsuite.diff +ensurepip-wheels.diff +ensurepip-disabled.diff +mangle-fstack-protector.diff +reproducible-buildinfo.diff +pydoc-use-pager.diff +issue27239.diff +rename-md5-init.diff +local-doc-references.diff +m-i-p-s-r6.diff +bpo-33570.diff +bpo-34818.diff +bpo-34834.diff +bpo-34836.diff --- python2.7-2.7.15.orig/debian/patches/setup-modules-ssl.diff +++ python2.7-2.7.15/debian/patches/setup-modules-ssl.diff @@ -0,0 +1,24 @@ +# DP: Modules/Setup.dist: patch to build _hashlib and _ssl extensions statically + +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -215,10 +215,7 @@ + + # Socket module helper for SSL support; you must comment out the other + # socket line above, and possibly edit the SSL variable: +-#SSL=/usr/local/ssl +-#_ssl _ssl.c \ +-# -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ +-# -L$(SSL)/lib -lssl -lcrypto ++#_ssl _ssl.c -lssl -lcrypto + + # The crypt module is now disabled by default because it breaks builds + # on many systems (where -lcrypt is needed), e.g. Linux (I believe). +@@ -261,6 +258,7 @@ + #_sha256 sha256module.c + #_sha512 sha512module.c + ++#_hashlib _hashopenssl.c -lssl -lcrypto + + # SGI IRIX specific modules -- off by default. + --- python2.7-2.7.15.orig/debian/patches/site-locations.diff +++ python2.7-2.7.15/debian/patches/site-locations.diff @@ -0,0 +1,32 @@ +# DP: Set site-packages/dist-packages + +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -19,6 +19,12 @@ + resulting directories, if they exist, are appended to sys.path, and + also inspected for path configuration files. + ++For Debian and derivatives, this sys.path is augmented with directories ++for packages distributed within the distribution. Local addons go ++into /usr/local/lib/python/dist-packages, Debian addons ++install into /usr/{lib,share}/python/dist-packages. ++/usr/lib/python/site-packages is not used. ++ + 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 +@@ -288,10 +294,12 @@ + if sys.platform in ('os2emx', 'riscos'): + sitepackages.append(os.path.join(prefix, "Lib", "site-packages")) + elif os.sep == '/': ++ sitepackages.append(os.path.join(prefix, "local/lib", ++ "python" + sys.version[:3], ++ "dist-packages")) + sitepackages.append(os.path.join(prefix, "lib", + "python" + sys.version[:3], +- "site-packages")) +- sitepackages.append(os.path.join(prefix, "lib", "site-python")) ++ "dist-packages")) + else: + sitepackages.append(prefix) + sitepackages.append(os.path.join(prefix, "lib", "site-packages")) --- python2.7-2.7.15.orig/debian/patches/sphinx-no-refcounting.diff +++ python2.7-2.7.15/debian/patches/sphinx-no-refcounting.diff @@ -0,0 +1,15 @@ +# DP: Use the included sphinx refcounting extension. + +Index: b/Doc/conf.py +=================================================================== +--- a/Doc/conf.py ++++ b/Doc/conf.py +@@ -13,7 +13,7 @@ + # General configuration + # --------------------- + +-extensions = ['sphinx.ext.refcounting', 'sphinx.ext.coverage', ++extensions = ['sphinx.ext.coverage', + 'sphinx.ext.doctest', 'pyspecific'] + templates_path = ['tools/sphinxext'] + --- python2.7-2.7.15.orig/debian/patches/statvfs-f_flag-constants.diff +++ python2.7-2.7.15/debian/patches/statvfs-f_flag-constants.diff @@ -0,0 +1,59 @@ +From 21fda4c78000d78cb1824fdf0373031d07f5325a Mon Sep 17 00:00:00 2001 +From: Peter Jones +Date: Wed, 6 Jan 2010 15:22:38 -0500 +Subject: [PATCH] Add flags for statvfs.f_flag to constant list. + +You really need these to figure out what statvfs is trying to say to +you, so add them here. +--- + Modules/posixmodule.c | 37 +++++++++++++++++++++++++++++++++++++ + 1 files changed, 37 insertions(+), 0 deletions(-) + +Index: b/Modules/posixmodule.c +=================================================================== +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -9428,6 +9428,43 @@ all_ins(PyObject *d) + if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; + #endif /* EX_NOTFOUND */ + ++ /* These came from statvfs.h */ ++#ifdef ST_RDONLY ++ if (ins(d, "ST_RDONLY", (long)ST_RDONLY)) return -1; ++#endif /* ST_RDONLY */ ++#ifdef ST_NOSUID ++ if (ins(d, "ST_NOSUID", (long)ST_NOSUID)) return -1; ++#endif /* ST_NOSUID */ ++ ++ /* GNU extensions */ ++#ifdef ST_NODEV ++ if (ins(d, "ST_NODEV", (long)ST_NODEV)) return -1; ++#endif /* ST_NODEV */ ++#ifdef ST_NOEXEC ++ if (ins(d, "ST_NOEXEC", (long)ST_NOEXEC)) return -1; ++#endif /* ST_NOEXEC */ ++#ifdef ST_SYNCHRONOUS ++ if (ins(d, "ST_SYNCHRONOUS", (long)ST_SYNCHRONOUS)) return -1; ++#endif /* ST_SYNCHRONOUS */ ++#ifdef ST_MANDLOCK ++ if (ins(d, "ST_MANDLOCK", (long)ST_MANDLOCK)) return -1; ++#endif /* ST_MANDLOCK */ ++#ifdef ST_WRITE ++ if (ins(d, "ST_WRITE", (long)ST_WRITE)) return -1; ++#endif /* ST_WRITE */ ++#ifdef ST_APPEND ++ if (ins(d, "ST_APPEND", (long)ST_APPEND)) return -1; ++#endif /* ST_APPEND */ ++#ifdef ST_NOATIME ++ if (ins(d, "ST_NOATIME", (long)ST_NOATIME)) return -1; ++#endif /* ST_NOATIME */ ++#ifdef ST_NODIRATIME ++ if (ins(d, "ST_NODIRATIME", (long)ST_NODIRATIME)) return -1; ++#endif /* ST_NODIRATIME */ ++#ifdef ST_RELATIME ++ if (ins(d, "ST_RELATIME", (long)ST_RELATIME)) return -1; ++#endif /* ST_RELATIME */ ++ + #ifdef HAVE_SPAWNV + #if defined(PYOS_OS2) && defined(PYCC_GCC) + if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; --- python2.7-2.7.15.orig/debian/patches/sys-multiarch.diff +++ python2.7-2.7.15/debian/patches/sys-multiarch.diff @@ -0,0 +1,25 @@ +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -1357,6 +1357,11 @@ + + Python/thread.o: @THREADHEADERS@ + ++Python/sysmodule.o: $(srcdir)/Python/sysmodule.c Makefile ++ $(CC) -c $(PY_CORE_CFLAGS) \ ++ -DMULTIARCH='"$(MULTIARCH)"' \ ++ -o $@ $(srcdir)/Python/sysmodule.c ++ + # Declare targets that aren't real files + .PHONY: all build_all sharedmods oldsharedmods test quicktest memtest + .PHONY: install altinstall oldsharedinstall bininstall altbininstall +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1435,6 +1435,8 @@ + PyFloat_GetInfo()); + SET_SYS_FROM_STRING("long_info", + PyLong_GetInfo()); ++ SET_SYS_FROM_STRING("_multiarch", ++ PyString_FromString(MULTIARCH)); + #ifdef Py_USING_UNICODE + SET_SYS_FROM_STRING("maxunicode", + PyInt_FromLong(PyUnicode_GetMax())); --- python2.7-2.7.15.orig/debian/patches/test-sundry.diff +++ python2.7-2.7.15/debian/patches/test-sundry.diff @@ -0,0 +1,19 @@ +# DP: test_sundry: Don't fail on import of the profile and pstats module + +Index: b/Lib/test/test_sundry.py +=================================================================== +--- a/Lib/test/test_sundry.py ++++ b/Lib/test/test_sundry.py +@@ -59,7 +59,11 @@ class TestUntestedModules(unittest.TestC + import os2emxpath + import pdb + import posixfile +- import pstats ++ try: ++ import pstats # separated out into the python-profiler package ++ except ImportError: ++ if test_support.verbose: ++ print "skipping profile and pstats" + import py_compile + import rexec + import sched --- python2.7-2.7.15.orig/debian/patches/tkinter-import.diff +++ python2.7-2.7.15/debian/patches/tkinter-import.diff @@ -0,0 +1,35 @@ +# DP: suggest installation of python-tk package on failing _tkinter import + +--- a/Lib/lib-tk/Tkinter.py ++++ b/Lib/lib-tk/Tkinter.py +@@ -36,7 +36,10 @@ + if sys.platform == "win32": + # Attempt to configure Tcl/Tk without requiring PATH + import FixTk +-import _tkinter # If this fails your Python may not be configured for Tk ++try: ++ import _tkinter ++except ImportError, msg: ++ raise ImportError, str(msg) + ', please install the python-tk package' + tkinter = _tkinter # b/w compat for export + TclError = _tkinter.TclError + from types import * +--- a/Demo/turtle/turtleDemo.py ++++ b/Demo/turtle/turtleDemo.py +@@ -3,10 +3,12 @@ + import os + + from Tkinter import * +-from idlelib.Percolator import Percolator +-from idlelib.ColorDelegator import ColorDelegator +-from idlelib.textView import view_file +- ++try: ++ from idlelib.Percolator import Percolator ++ from idlelib.ColorDelegator import ColorDelegator ++ from idlelib.textView import view_file ++except ImportError, msg: ++ raise ImportError, str(msg) + ', please install the idle package' + import turtle + import time + --- python2.7-2.7.15.orig/debian/pdb.1.in +++ python2.7-2.7.15/debian/pdb.1.in @@ -0,0 +1,16 @@ +.TH PDB@VER@ 1 +.SH NAME +pdb@VER@ \- the Python debugger +.SH SYNOPSIS +.PP +.B pdb@VER@ +.I script [...] +.SH DESCRIPTION +.PP +See /usr/lib/python@VER@/pdb.doc for more information on the use +of pdb. When the debugger is started, help is available via the +help command. +.SH SEE ALSO +python@VER@(1). Chapter 9 of the Python Library Reference +(The Python Debugger). Available in the python@VER@-doc package at +/usr/share/doc/python@VER@/html/lib/module-pdb.html. --- python2.7-2.7.15.orig/debian/pydoc.1.in +++ python2.7-2.7.15/debian/pydoc.1.in @@ -0,0 +1,53 @@ +.TH PYDOC@VER@ 1 +.SH NAME +pydoc@VER@ \- the Python documentation tool +.SH SYNOPSIS +.PP +.B pydoc@VER@ +.I name +.PP +.B pydoc@VER@ -k +.I keyword +.PP +.B pydoc@VER@ -p +.I port +.PP +.B pydoc@VER@ -g +.PP +.B pydoc@VER@ -w +.I module [...] +.SH DESCRIPTION +.PP +.B pydoc@VER@ +.I name +Show text documentation on something. +.I name +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 +.I name +contains a '/', 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. +.PP +.B pydoc@VER@ -k +.I keyword +Search for a keyword in the synopsis lines of all available modules. +.PP +.B pydoc@VER@ -p +.I port +Start an HTTP server on the given port on the local machine. +.PP +.B pydoc@VER@ -g +Pop up a graphical interface for finding and serving documentation. +.PP +.B pydoc@VER@ -w +.I name [...] +Write out the HTML documentation for a module to a file in the current +directory. If +.I name +contains a '/', it is treated as a filename; if +it names a directory, documentation is written for all the contents. +.SH AUTHOR +Moshe Zadka, based on "pydoc --help" --- python2.7-2.7.15.orig/debian/pyfpe-breaks.Debian +++ python2.7-2.7.15/debian/pyfpe-breaks.Debian @@ -0,0 +1,70 @@ +cython (<< 0.26-2.1), +python-lxml (<< 3.8.0-2), +python-numpy (<< 1:1.12.1-3.1), +python-tk (<< 2.7.14~rc1-1~), +python-scipy (<< 0.18.1-2.1), +epigrass (<= 2.4.7-1), +invesalius-bin (<= 3.1.1-1), +macs (<= 2.1.1.20160309-1), +printrun (<= 0~20150310-5), +pycorrfit (<= 1.0.0+dfsg-1), +pyscanfcs (<= 0.2.3-3), +python-acora (<= 2.0-2+b1), +python-adios (<= 1.12.0-3), +python-astroml-addons (<= 0.2.2-4), +python-astropy (<= 2.0.1-2), +python-astroscrappy (<= 1.0.5-1+b1), +python-bcolz (<= 1.1.0+ds1-4+b1), +python-breezy (<= 3.0.0~bzr6772-1), +python-bzrlib (<= 2.7.0+bzr6622-7), +python-cartopy (<= 0.14.2+dfsg1-2+b1), +python-cogent (<= 1.9-11), +python-cutadapt (<= 1.13-1+b1), +python-cypari2 (<= 1.0.0-3), +python-dipy-lib (<= 0.12.0-1), +python-djvu (<= 0.8-2), +python-fabio (<= 0.4.0+dfsg-2+b1), +python-falcon (<= 1.0.0-2+b1), +python-fiona (<= 1.7.9-1), +python-fpylll (<= 0.2.4+ds-3), +python-grib (<= 2.0.2-2), +python-gssapi (<= 1.2.0-1+b1), +python-h5py (<= 2.7.0-1+b1), +python-healpy (<= 1.10.3-2+b1), +python-htseq (<= 0.6.1p1-4), +python-imobiledevice (<= 1.2.0+dfsg-3.1), +python-kivy (<= 1.9.1-1+b1), +python-libdiscid (<= 1.0-1+b1), +python-liblo (<= 0.10.0-3+b1), +python-llfuse (<= 1.2+dfsg-1+b1), +python-meliae (<= 0.4.0+bzr199-3), +python-netcdf4 (<= 1.2.9-1+b1), +python-nipy-lib (<= 0.4.1-1), +python-pandas-lib (<= 0.20.3-1), +python-petsc4py (<= 3.7.0-3+b1), +python-pybloomfiltermmap (<= 0.3.15-0.1+b1), +python-pyfai (<= 0.13.0+dfsg-1+b1), +python-pygame-sdl2 (<= 6.99.12.4-1), +python-pygpu (<= 0.6.9-2), +python-pymca5 (<= 5.1.3+dfsg-1+b1), +python-pymssql (<= 2.1.3+dfsg-1+b1), +python-pyresample (<= 1.5.0-3+b1), +python-pysam (<= 0.11.2.2+ds-3), +python-pysph (<= 0~20160514.git91867dc-4), +python-pywt (<= 0.5.1-1.1+b1), +python-rasterio (<= 0.36.0-2+b2), +python-renpy (<= 6.99.12.4+dfsg-1), +python-sfepy (<= 2016.2-2), +python-sfml (<= 2.2~git20150611.196c88+dfsg-4), +python-shapely (<= 1.6.1-1), +python-skimage-lib (<= 0.12.3-9+b1), +python-sklearn-lib (<= 0.19.0-1), +python-specutils (<= 0.2.2-1+b1), +python-statsmodels-lib (<= 0.8.0-3), +python-stemmer (<= 1.3.0+dfsg-1+b7), +python-tables-lib (<= 3.3.0-5+b1), +python-tinycss (<= 0.4-1+b1), +python-wheezy.template (<= 0.1.167-1.1+b1), +python-yt (<= 3.3.3-2+b1), +sagemath (<= 8.0-5), +xpra (<= 0.17.6+dfsg-1), --- python2.7-2.7.15.orig/debian/pyfpe-breaks.Ubuntu +++ python2.7-2.7.15/debian/pyfpe-breaks.Ubuntu @@ -0,0 +1,5 @@ +cython (<< 0.25.2-2build3), +python-lxml (<< 3.8.0-2), +python-numpy (<< 1:1.12.1-3.1ubuntu1), +python-tk (<< 2.7.14~rc1-1~), +python-scipy (<< 0.18.1-2ubuntu3), --- python2.7-2.7.15.orig/debian/pygettext.1 +++ python2.7-2.7.15/debian/pygettext.1 @@ -0,0 +1,108 @@ +.TH PYGETTEXT 1 "" "pygettext 1.4" +.SH NAME +pygettext \- Python equivalent of xgettext(1) +.SH SYNOPSIS +.B pygettext +[\fIOPTIONS\fR] \fIINPUTFILE \fR... +.SH DESCRIPTION +pygettext is deprecated. The current version of xgettext supports +many languages, including Python. + +pygettext uses Python's standard tokenize module to scan Python +source code, generating .pot files identical to what GNU xgettext generates +for C and C++ code. From there, the standard GNU tools can be used. +.PP +pygettext searches only for _() by default, even though GNU xgettext +recognizes the following keywords: gettext, dgettext, dcgettext, +and gettext_noop. See the \fB\-k\fR/\fB\--keyword\fR flag below for how to +augment this. +.PP +.SH OPTIONS +.TP +\fB\-a\fR, \fB\-\-extract\-all\fR +Extract all strings. +.TP +\fB\-d\fR, \fB\-\-default\-domain\fR=\fINAME\fR +Rename the default output file from messages.pot to name.pot. +.TP +\fB\-E\fR, \fB\-\-escape\fR +Replace non-ASCII characters with octal escape sequences. +.TP +\fB\-D\fR, \fB\-\-docstrings\fR +Extract module, class, method, and function docstrings. +These do not need to be wrapped in _() markers, and in fact cannot +be for Python to consider them docstrings. (See also the \fB\-X\fR option). +.TP +\fB\-h\fR, \fB\-\-help\fR +Print this help message and exit. +.TP +\fB\-k\fR, \fB\-\-keyword\fR=\fIWORD\fR +Keywords to look for in addition to the default set, which are: _ +.IP +You can have multiple \fB\-k\fR flags on the command line. +.TP +\fB\-K\fR, \fB\-\-no\-default\-keywords\fR +Disable the default set of keywords (see above). +Any keywords explicitly added with the \fB\-k\fR/\fB\--keyword\fR option +are still recognized. +.TP +\fB\-\-no\-location\fR +Do not write filename/lineno location comments. +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +Write filename/lineno location comments indicating where each +extracted string is found in the source. These lines appear before +each msgid. The style of comments is controlled by the +\fB\-S\fR/\fB\--style\fR option. This is the default. +.TP +\fB\-o\fR, \fB\-\-output\fR=\fIFILENAME\fR +Rename the default output file from messages.pot to FILENAME. +If FILENAME is `-' then the output is sent to standard out. +.TP +\fB\-p\fR, \fB\-\-output\-dir\fR=\fIDIR\fR +Output files will be placed in directory DIR. +.TP +\fB\-S\fR, \fB\-\-style\fR=\fISTYLENAME\fR +Specify which style to use for location comments. +Two styles are supported: +.RS +.IP \(bu 4 +Solaris # File: filename, line: line-number +.IP \(bu 4 +GNU #: filename:line +.RE +.IP +The style name is case insensitive. +GNU style is the default. +.TP +\fB\-v\fR, \fB\-\-verbose\fR +Print the names of the files being processed. +.TP +\fB\-V\fR, \fB\-\-version\fR +Print the version of pygettext and exit. +.TP +\fB\-w\fR, \fB\-\-width\fR=\fICOLUMNS\fR +Set width of output to columns. +.TP +\fB\-x\fR, \fB\-\-exclude\-file\fR=\fIFILENAME\fR +Specify a file that contains a list of strings that are not be +extracted from the input files. Each string to be excluded must +appear on a line by itself in the file. +.TP +\fB\-X\fR, \fB\-\-no\-docstrings\fR=\fIFILENAME\fR +Specify a file that contains a list of files (one per line) that +should not have their docstrings extracted. This is only useful in +conjunction with the \fB\-D\fR option above. +.PP +If `INPUTFILE' is -, standard input is read. +.SH BUGS +pygettext attempts to be option and feature compatible with GNU xgettext +where ever possible. However some options are still missing or are not fully +implemented. Also, xgettext's use of command line switches with option +arguments is broken, and in these cases, pygettext just defines additional +switches. +.SH AUTHOR +pygettext is written by Barry Warsaw . +.PP +Joonas Paalasmaa put this manual page together +based on "pygettext --help". --- python2.7-2.7.15.orig/debian/pyhtml2devhelp.py +++ python2.7-2.7.15/debian/pyhtml2devhelp.py @@ -0,0 +1,222 @@ +#! /usr/bin/python + +import formatter, htmllib +import os, sys, re + +class PyHTMLParser(htmllib.HTMLParser): + pages_to_include = set(('whatsnew/index.html', 'tutorial/index.html', 'using/index.html', + 'reference/index.html', 'library/index.html', 'howto/index.html', + 'extending/index.html', 'c-api/index.html', 'install/index.html', + 'distutils/index.html')) + + def __init__(self, formatter, basedir, fn, indent, parents=set()): + htmllib.HTMLParser.__init__(self, formatter) + self.basedir = basedir + self.dir, self.fn = os.path.split(fn) + self.data = '' + self.parents = parents + self.link = {} + self.indent = indent + self.last_indent = indent - 1 + self.sub_indent = 0 + self.sub_count = 0 + self.next_link = False + + def process_link(self): + new_href = os.path.join(self.dir, self.link['href']) + text = self.link['text'] + indent = self.indent + self.sub_indent + if self.last_indent == indent: + print '%s' % (' ' * self.last_indent) + self.sub_count -= 1 + print '%s' % (' ' * indent, new_href, text) + self.sub_count += 1 + self.last_indent = self.indent + self.sub_indent + + def start_li(self, attrs): + self.sub_indent += 1 + self.next_link = True + + def end_li(self): + indent = self.indent + self.sub_indent + if self.sub_count > 0: + print '%s' % (' ' * self.last_indent) + self.sub_count -= 1 + self.last_indent -= 1 + self.sub_indent -= 1 + + def start_a(self, attrs): + self.link = {} + for attr in attrs: + self.link[attr[0]] = attr[1] + self.data = '' + + def end_a(self): + process = False + text = self.data.replace('\t', '').replace('\n', ' ').replace('&', '&').replace('<', '<').replace('>', '>') + self.link['text'] = text + # handle a tag without href attribute + try: + href = self.link['href'] + except KeyError: + return + + abs_href = os.path.join(self.basedir, href) + if abs_href in self.parents: + return + if href.startswith('..') or href.startswith('http:') \ + or href.startswith('mailto:') or href.startswith('news:'): + return + if href in ('', 'about.html', 'modindex.html', 'genindex.html', 'glossary.html', + 'search.html', 'contents.html', 'download.html', 'bugs.html', + 'license.html', 'copyright.html'): + return + + if self.link.has_key('class'): + if self.link['class'] in ('biglink'): + process = True + if self.link['class'] in ('reference external'): + if self.next_link: + process = True + next_link = False + + if process == True: + self.process_link() + if href in self.pages_to_include: + self.parse_file(os.path.join(self.dir, href)) + + def finish(self): + if self.sub_count > 0: + print '%s' % (' ' * self.last_indent) + + def handle_data(self, data): + self.data += data + + def parse_file(self, href): + # TODO basedir bestimmen + parent = os.path.join(self.basedir, self.fn) + self.parents.add(parent) + parser = PyHTMLParser(formatter.NullFormatter(), + self.basedir, href, self.indent + 1, + self.parents) + text = file(self.basedir + '/' + href).read() + parser.feed(text) + parser.finish() + parser.close() + if parent in self.parents: + self.parents.remove(parent) + +class PyIdxHTMLParser(htmllib.HTMLParser): + def __init__(self, formatter, basedir, fn, indent): + htmllib.HTMLParser.__init__(self, formatter) + self.basedir = basedir + self.dir, self.fn = os.path.split(fn) + self.data = '' + self.link = {} + self.indent = indent + self.active = False + self.indented = False + self.nolink = False + self.header = '' + self.last_letter = 'Z' + self.last_text = '' + + def process_link(self): + new_href = os.path.join(self.dir, self.link['href']) + text = self.link['text'] + if not self.active: + return + if text.startswith('['): + return + if self.link.get('rel', None) in ('prev', 'parent', 'next', 'contents', 'index'): + return + if self.indented: + text = self.last_text + ' ' + text + else: + # Save it in case we need it again + self.last_text = re.sub(' \([\w\-\.\s]+\)', '', text) + indent = self.indent + print '%s' % (' ' * indent, new_href, text) + + def start_dl(self, attrs): + if self.last_text: + # Looks like we found the second part to a command + self.indented = True + + def end_dl(self): + self.indented = False + + def start_dt(self, attrs): + self.data = '' + self.nolink = True + + def end_dt(self): + if not self.active: + return + if self.nolink == True: + # Looks like we found the first part to a command + self.last_text = re.sub(' \([\w\-\.\s]+\)', '', self.data) + self.nolink = False + + def start_h2(self, attrs): + for k, v in attrs: + if k == 'id': + self.header = v + if v == '_': + self.active = True + + def start_td(self, attrs): + self.indented = False + self.last_text = '' + + def start_table(self, attrs): + pass + + def end_table(self): + if self.header == self.last_letter: + self.active = False + + def start_a(self, attrs): + self.nolink = False + self.link = {} + for attr in attrs: + self.link[attr[0]] = attr[1] + self.data = '' + + def end_a(self): + text = self.data.replace('\t', '').replace('\n', ' ').replace('&', '&').replace('<', '<').replace('>', '>') + self.link['text'] = text + # handle a tag without href attribute + try: + href = self.link['href'] + except KeyError: + return + self.process_link() + + def handle_data(self, data): + self.data += data + +def main(): + base = sys.argv[1] + fn = sys.argv[2] + version = sys.argv[3] + + parser = PyHTMLParser(formatter.NullFormatter(), base, fn, indent=0) + print '' + print '' % (version, version) + print '' + parser.parse_file(fn) + print '' + + print '' + + fn = 'genindex-all.html' + parser = PyIdxHTMLParser(formatter.NullFormatter(), base, fn, indent=1) + text = file(base + '/' + fn).read() + parser.feed(text) + parser.close() + + print '' + print '' + +main() --- python2.7-2.7.15.orig/debian/pylogo.xpm +++ python2.7-2.7.15/debian/pylogo.xpm @@ -0,0 +1,351 @@ +/* XPM */ +static char * pylogo_xpm[] = { +"32 32 316 2", +" c None", +". c #8DB0CE", +"+ c #6396BF", +"@ c #4985B7", +"# c #4181B5", +"$ c #417EB2", +"% c #417EB1", +"& c #4D83B0", +"* c #6290B6", +"= c #94B2CA", +"- c #70A1C8", +"; c #3D83BC", +"> c #3881BD", +", c #387DB6", +"' c #387CB5", +") c #387BB3", +"! c #3779B0", +"~ c #3778AE", +"{ c #3776AB", +"] c #3776AA", +"^ c #3775A9", +"/ c #4A7FAC", +"( c #709FC5", +"_ c #3A83BE", +": c #5795C7", +"< c #94B9DB", +"[ c #73A4CE", +"} c #3D80B7", +"| c #387CB4", +"1 c #377AB2", +"2 c #377AB0", +"3 c #3777AC", +"4 c #3774A7", +"5 c #3773A5", +"6 c #3C73A5", +"7 c #4586BB", +"8 c #4489C1", +"9 c #A7C7E1", +"0 c #F7F9FD", +"a c #E1E9F1", +"b c #4C89BC", +"c c #3779AF", +"d c #3778AD", +"e c #3873A5", +"f c #4B7CA4", +"g c #3982BE", +"h c #4389C1", +"i c #A6C6E1", +"j c #F6F9FC", +"k c #D6E4F0", +"l c #4A88BB", +"m c #3773A6", +"n c #366F9F", +"o c #366E9D", +"p c #376E9C", +"q c #4A8BC0", +"r c #79A7CD", +"s c #548EBD", +"t c #387AB0", +"u c #3773A4", +"v c #366D9C", +"w c #387FBA", +"x c #387DB7", +"y c #387BB4", +"z c #3775A8", +"A c #366FA0", +"B c #4981AF", +"C c #427BAA", +"D c #3772A4", +"E c #376B97", +"F c #77A3C8", +"G c #4586BC", +"H c #3882BE", +"I c #3B76A7", +"J c #3B76A6", +"K c #366E9E", +"L c #376B98", +"M c #376B96", +"N c #5681A3", +"O c #F5EEB8", +"P c #FFED60", +"Q c #FFE85B", +"R c #FFE659", +"S c #FDE55F", +"T c #5592C4", +"U c #3A83BF", +"V c #3882BD", +"W c #387FB9", +"X c #3779AE", +"Y c #366F9E", +"Z c #366C98", +"` c #376A94", +" . c #5D85A7", +".. c #F5EDB7", +"+. c #FFEA5D", +"@. c #FFE75A", +"#. c #FFE354", +"$. c #FDDD56", +"%. c #669DC8", +"&. c #3885C3", +"*. c #3884C2", +"=. c #387EB8", +"-. c #387CB6", +";. c #377AB1", +">. c #3772A3", +",. c #366D9B", +"'. c #F5EBB5", +"). c #FFE557", +"!. c #FFE455", +"~. c #FFDF50", +"{. c #FFDB4C", +"]. c #FAD862", +"^. c #8EB4D2", +"/. c #3C86C1", +"(. c #3883C0", +"_. c #3882BF", +":. c #3881BC", +"<. c #3880BB", +"[. c #3775AA", +"}. c #F5EAB3", +"|. c #FFE051", +"1. c #FFDE4F", +"2. c #FFDA4A", +"3. c #FED446", +"4. c #F5DF9D", +"5. c #77A5CA", +"6. c #3885C2", +"7. c #387BB2", +"8. c #6B8EA8", +"9. c #F8E7A1", +"0. c #FFE153", +"a. c #FFDD4E", +"b. c #FFDB4B", +"c. c #FFD746", +"d. c #FFD645", +"e. c #FFD342", +"f. c #F6DB8D", +"g. c #508DBE", +"h. c #3771A3", +"i. c #376A95", +"j. c #3D6F97", +"k. c #C3CBC2", +"l. c #FBD964", +"m. c #FFDC4D", +"n. c #FFD544", +"o. c #FFD040", +"p. c #F9CF58", +"q. c #3F83BB", +"r. c #376B95", +"s. c #3A6C95", +"t. c #4E7BA0", +"u. c #91AABC", +"v. c #F6E4A3", +"w. c #FFDA4B", +"x. c #FFD646", +"y. c #FFD443", +"z. c #FFD241", +"A. c #FFCE3D", +"B. c #FFCC3B", +"C. c #FCC83E", +"D. c #3880BC", +"E. c #3C79AC", +"F. c #5F8DB4", +"G. c #7AA0C0", +"H. c #82A6C3", +"I. c #82A3BF", +"J. c #82A2BE", +"K. c #82A1BB", +"L. c #82A1B9", +"M. c #8BA4B5", +"N. c #C1C5AE", +"O. c #F2E19F", +"P. c #FDD74C", +"Q. c #FFD94A", +"R. c #FFD343", +"S. c #FFCE3E", +"T. c #FFCB39", +"U. c #FFC937", +"V. c #FEC636", +"W. c #3D79AB", +"X. c #9DB6C6", +"Y. c #D0CFA2", +"Z. c #EFE598", +"`. c #F8EE9B", +" + c #F8EB97", +".+ c #F8E996", +"++ c #F8E894", +"@+ c #FAE489", +"#+ c #FCDB64", +"$+ c #FFDA4D", +"%+ c #FFCF3E", +"&+ c #FFCB3A", +"*+ c #FFC734", +"=+ c #FFC532", +"-+ c #3F82B7", +";+ c #387EB9", +">+ c #9EB9D0", +",+ c #F2E287", +"'+ c #FDEB69", +")+ c #FEEC60", +"!+ c #FFEB5E", +"~+ c #FFE254", +"{+ c #FFE152", +"]+ c #FFD747", +"^+ c #FFC633", +"/+ c #FCC235", +"(+ c #578FBE", +"_+ c #6996BC", +":+ c #DED9A8", +"<+ c #FEEC62", +"[+ c #FFE658", +"}+ c #FFDF51", +"|+ c #FFDE50", +"1+ c #FFD03F", +"2+ c #FFCD3C", +"3+ c #FFC431", +"4+ c #FFBF2C", +"5+ c #FAC244", +"6+ c #85AACA", +"7+ c #A1BBD2", +"8+ c #F7E47C", +"9+ c #FFE456", +"0+ c #FFC735", +"a+ c #FFBC29", +"b+ c #F7D280", +"c+ c #9DBAD2", +"d+ c #3B7CB2", +"e+ c #ABC2D6", +"f+ c #FDEB7B", +"g+ c #FFC12E", +"h+ c #FDBD30", +"i+ c #F4DEA8", +"j+ c #5F91BA", +"k+ c #ABC1D4", +"l+ c #FDEE7E", +"m+ c #FFE253", +"n+ c #FFCC3C", +"o+ c #FFBA27", +"p+ c #FAC75B", +"q+ c #4A82B0", +"r+ c #3877AB", +"s+ c #3774A6", +"t+ c #AAC0D4", +"u+ c #FDEE7D", +"v+ c #FFEC5F", +"w+ c #FFE255", +"x+ c #FFD848", +"y+ c #FFD444", +"z+ c #FFCF3F", +"A+ c #FFBC2A", +"B+ c #FFBB28", +"C+ c #FDBA32", +"D+ c #447AA8", +"E+ c #4379A7", +"F+ c #FFE95C", +"G+ c #FFE558", +"H+ c #FFE355", +"I+ c #FED84B", +"J+ c #FCD149", +"K+ c #FBCE47", +"L+ c #FBCD46", +"M+ c #FBC840", +"N+ c #FBC63E", +"O+ c #FBC037", +"P+ c #FAC448", +"Q+ c #FDD44C", +"R+ c #FCD14E", +"S+ c #FFC836", +"T+ c #FFC22F", +"U+ c #FFC02D", +"V+ c #FFE052", +"W+ c #FFC636", +"X+ c #FFCF5C", +"Y+ c #FFD573", +"Z+ c #FFC33E", +"`+ c #FEBD2D", +" @ c #FFDB4D", +".@ c #FFD949", +"+@ c #FFD545", +"@@ c #FFD140", +"#@ c #FFCB48", +"$@ c #FFF7E4", +"%@ c #FFFCF6", +"&@ c #FFE09D", +"*@ c #FFBA2E", +"=@ c #FDBE2F", +"-@ c #FFD748", +";@ c #FFCA38", +">@ c #FFC844", +",@ c #FFF2D7", +"'@ c #FFF9EC", +")@ c #FFDB94", +"!@ c #FFB92D", +"~@ c #FAC54D", +"{@ c #FDD54E", +"]@ c #FFBD2D", +"^@ c #FFC858", +"/@ c #FFD174", +"(@ c #FFBF3E", +"_@ c #FCBD3C", +":@ c #FAD66A", +"<@ c #FECD3F", +"[@ c #FFC330", +"}@ c #FFBD2A", +"|@ c #FFB724", +"1@ c #FFB521", +"2@ c #FFB526", +"3@ c #FBC457", +"4@ c #F7E09E", +"5@ c #F8D781", +"6@ c #FAC349", +"7@ c #FCC134", +"8@ c #FEBE2C", +"9@ c #FBBE3F", +"0@ c #F7CF79", +"a@ c #F5D795", +" . + @ # $ % % & * = ", +" - ; > > , ' ) ! ~ { ] ^ / ", +" ( _ : < [ } | 1 2 ~ 3 4 5 5 6 ", +" 7 8 9 0 a b 2 c d 3 { 5 5 5 e f ", +" g h i j k l c ~ { { m 5 5 n o p ", +" > > q r s t c c d 4 5 u n v v v ", +" w x ' y 2 c d d z 5 u A v v v v ", +" B C 5 D v v v v E ", +" F G H H H x ' ) c c c d I J 5 K v v L M N O P Q R S ", +" T U H V V W ' ) c c X ~ 5 5 5 Y v v Z ` ` ...+.@.#.#.$. ", +" %.&.*.> w W =.-.;.c 3 { ^ 5 5 >.o v ,.E ` ` .'.).!.#.~.{.]. ", +"^./.(._.:.<., ' ) ;.X d [.5 5 >.K v ,.E ` ` ` .}.#.|.1.{.2.3.4.", +"5.6.(.H H x ' 7.c c 3 3 4 5 D K v v ,.` ` ` ` 8.9.0.a.b.c.d.e.f.", +"g._.> <.w ' ' | 2 3 { z 5 5 h.v v v i.` ` ` j.k.l.m.{.d.n.e.o.p.", +"q.> > :.-.' 1 c c c ] 5 5 >.v v ,.r.` ` s.t.u.v.{.w.x.y.z.A.B.C.", +"D.D.w -.' 1 c c c E.F.G.H.I.J.J.K.L.L.L.M.N.O.P.Q.c.R.S.B.T.U.V.", +"D.D.=.' ' 1 c c W.X.Y.Z.`.`.`.`.`. +.+++@+#+$+Q.d.R.%+B.&+*+=+=+", +"-+;+-.' ;.2 c c >+,+'+)+P P P !+Q R ~+{+1.{.]+d.y.%+B.&+^+=+=+/+", +"(+' ' ;.c X X _+:+<+P P P P !+R [+~+}+|+{.]+n.R.1+2+&+^+=+3+4+5+", +"6+' ) ! ~ { { 7+8+P P P P !+R 9+#.{+{.w.]+y.z.S.&+0+=+=+3+4+a+b+", +"c+d+7.! d 3 z e+f+P P P !+R 9+#.{+m.{.]+y.1+B.&+0+=+=+g+4+a+h+i+", +" j+c d 3 { 4 k+l+P P !+@.9+m+1.m.{.]+y.1+n+B.*+=+=+g+a+a+o+p+ ", +" q+r+{ s+m t+u+v+@.R w+{+}+{.x+d.y+z+n+B.0+=+=+g+A+a+B+C+ ", +" * D+E+E+ +.F+G+H+}+}+{.I+J+K+L+M+M+M+M+N+O+O+O+O+P+ ", +" ).).#.{+a.{.x+Q+R+ ", +" #.m+1.a.{.x+y.o.2+B.S+=+=+T+U+O+ ", +" 0.V+{.{.x+n.o.2+B.B.W+X+Y+Z+a+`+ ", +" @{..@+@n.@@B.B.S+^+#@$@%@&@*@=@ ", +" ].-@x.y.o.%+;@S+=+=+>@,@'@)@!@~@ ", +" {@z.z+2+U.=+=+=+T+]@^@/@(@_@ ", +" :@<@U.=+=+[@4+}@|@1@2@3@ ", +" 4@5@6@7@8@a+a+9@0@a@ "}; --- python2.7-2.7.15.orig/debian/pymindeps.py +++ python2.7-2.7.15/debian/pymindeps.py @@ -0,0 +1,174 @@ +#! /usr/bin/python + +# Matthias Klose +# Modified to only exclude module imports from a given module. + +# Copyright 2004 Toby Dickenson +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject +# to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import os, sys, pprint +import modulefinder +import imp + +class mymf(modulefinder.ModuleFinder): + def __init__(self,*args,**kwargs): + self._depgraph = {} + self._types = {} + self._last_caller = None + modulefinder.ModuleFinder.__init__(self, *args, **kwargs) + + def import_hook(self, name, caller=None, fromlist=None, level=-1): + old_last_caller = self._last_caller + try: + self._last_caller = caller + return modulefinder.ModuleFinder.import_hook(self, name, caller, + fromlist, level) + finally: + self._last_caller = old_last_caller + + def import_module(self, partnam, fqname, parent): + m = modulefinder.ModuleFinder.import_module(self, + partnam, fqname, parent) + if m is not None and self._last_caller: + caller = self._last_caller.__name__ + if '.' in caller: + caller = caller[:caller.index('.')] + callee = m.__name__ + if '.' in callee: + callee = callee[:callee.index('.')] + #print "XXX last_caller", caller, "MOD", callee + #self._depgraph.setdefault(self._last_caller.__name__,{})[r.__name__] = 1 + #if caller in ('pdb', 'doctest') or callee in ('pdb', 'doctest'): + # print caller, "-->", callee + if caller != callee: + self._depgraph.setdefault(caller,{})[callee] = 1 + return m + + def find_module(self, name, path, parent=None): + if parent is not None: + # assert path is not None + fullname = parent.__name__+'.'+name + elif name == "__init__": + fullname = os.path.basename(path[0]) + else: + fullname = name + if self._last_caller: + caller = self._last_caller.__name__ + if fullname in excluded_imports.get(caller, []): + #self.msgout(3, "find_module -> Excluded", fullname) + raise ImportError, name + + if fullname in self.excludes: + #self.msgout(3, "find_module -> Excluded", fullname) + raise ImportError, name + + if path is None: + if name in sys.builtin_module_names: + return (None, None, ("", "", imp.C_BUILTIN)) + + path = self.path + return imp.find_module(name, path) + + def load_module(self, fqname, fp, pathname, file_info): + suffix, mode, type = file_info + m = modulefinder.ModuleFinder.load_module(self, fqname, + fp, pathname, file_info) + if m is not None: + self._types[m.__name__] = type + return m + + def load_package(self, fqname, pathname): + m = modulefinder.ModuleFinder.load_package(self, fqname,pathname) + if m is not None: + self._types[m.__name__] = imp.PKG_DIRECTORY + return m + +def reduce_depgraph(dg): + pass + +# guarded imports, which don't need to be included in python-minimal +excluded_imports = { + 'collections': set(('doctest', 'dummy_thread', 'cPickle')), + 'copy': set(('reprlib',)), + 'difflib': set(('doctest',)), + 'hashlib': set(('logging',)), + 'hashlib': set(('_hashlib', '_md5', '_sha', '_sha256','_sha512',)), + 'heapq': set(('doctest',)), + 'inspect': set(('compiler',)), + 'os': set(('nt', 'ntpath', 'os2', 'os2emxpath', 'mac', 'macpath', + 'riscos', 'riscospath', 'riscosenviron')), + 'optparse': set(('gettext',)), + 'pickle': set(('doctest',)), + 'platform': set(('ctypes', 'plistlib', 'tempfile', 'winreg')), + #'socket': set(('_ssl', 'ssl')), + 'tempfile': set(('dummy_thread',)), + 'subprocess': set(('threading',)), + 'shutil': set(('bz2', 'distutils', 'tarfile', 'zipfile')), + 'sysconfig': set(('pprint', '_osx_support')), + } + +def main(argv): + # Parse command line + import getopt + try: + opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") + except getopt.error as msg: + print(msg) + return + + # Process options + debug = 1 + domods = 0 + addpath = [] + exclude = [] + for o, a in opts: + if o == '-d': + debug = debug + 1 + if o == '-m': + domods = 1 + if o == '-p': + addpath = addpath + a.split(os.pathsep) + if o == '-q': + debug = 0 + if o == '-x': + exclude.append(a) + + path = sys.path[:] + path = addpath + path + + if debug > 1: + print("version:", sys.version) + print("path:") + for item in path: + print(" ", repr(item)) + + #exclude = ['__builtin__', 'sys', 'os'] + exclude = [] + mf = mymf(path, debug, exclude) + for arg in args: + mf.run_script(arg) + + depgraph = reduce_depgraph(mf._depgraph) + + pprint.pprint({'depgraph':mf._depgraph, 'types':mf._types}) + +if __name__=='__main__': + main(sys.argv[1:]) --- python2.7-2.7.15.orig/debian/python-config.1 +++ python2.7-2.7.15/debian/python-config.1 @@ -0,0 +1,102 @@ +.TH PYTHON\-CONFIG 1 "November 27, 2011" +.SH NAME +python\-config \- output build options for python C/C++ extensions or embedding +.SH SYNOPSIS +.BI "python\-config" +[ +.BI "\-\-prefix" +] +[ +.BI "\-\-exec\-prefix" +] +[ +.BI "\-\-includes" +] +[ +.BI "\-\-libs" +] +[ +.BI "\-\-cflags" +] +[ +.BI "\-\-ldflags" +] +[ +.BI "\-\-extension\-suffix" +] +[ +.BI "\-\-configdir" +] +[ +.BI "\-\-help" +] +.SH DESCRIPTION +.B python\-config +helps compiling and linking programs, which embed the Python interpreter, or +extension modules that can be loaded dynamically (at run time) into +the interpreter. +.SH OPTIONS +.TP +.BI "\-\-cflags" +print the C compiler flags. +.TP +.BI "\-\-ldflags" +print the flags that should be passed to the linker. +.TP +.BI "\-\-includes" +similar to \fI\-\-cflags\fP but only with \-I options (path to python header files). +.TP +.BI "\-\-libs" +similar to \fI\-\-ldflags\fP but only with \-l options (used libraries). +.TP +.BI "\-\-prefix" +prints the prefix (base directory) under which python can be found. +.TP +.BI "\-\-exec\-prefix" +print the prefix used for executable program directories (such as bin, sbin, etc). +.TP +.BI "\-\-extension\-suffix" +print suffix used for extension modules (including the _d modified for debug builds). +.TP +.BI "\-\-configdir" +prints the path to the configuration directory under which the Makefile, etc. can be found). +.TP +.BI "\-\-help" +print the usage message. +.PP + +.SH EXAMPLES +To build the singe\-file c program \fIprog\fP against the python library, use +.PP +.RS +gcc $(python\-config \-\-cflags \-\-ldflags) progr.cpp \-o progr.cpp +.RE +.PP +The same in a makefile: +.PP +.RS +CFLAGS+=$(shell python\-config \-\-cflags) +.RE +.RS +LDFLAGS+=$(shell python\-config \-\-ldflags) +.RE +.RS +all: progr +.RE + +To build a dynamically loadable python module, use +.PP +.RS +gcc $(python\-config \-\-cflags \-\-ldflags) \-shared \-fPIC progr.cpp \-o progr.so +.RE + +.SH "SEE ALSO" +python (1) +.br +http://docs.python.org/extending/extending.html +.br +/usr/share/doc/python/faq/extending.html + +.SH AUTHORS +This manual page was written by Johann Felix Soden +for the Debian project (and may be used by others). --- python2.7-2.7.15.orig/debian/rules +++ python2.7-2.7.15/debian/rules @@ -0,0 +1,1457 @@ +#!/usr/bin/make -f + +unexport LANG LC_ALL LC_CTYPE LC_COLLATE LC_TIME LC_NUMERIC LC_MESSAGES +unexport CFLAGS CXXFLAGS CPPFLAGS LDFLAGS + +export SHELL = /bin/bash + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + +vafilt = $(subst $(2)=,,$(filter $(2)=%,$(1))) + +DPKG_VARS := $(shell dpkg-architecture) +DEB_BUILD_ARCH ?= $(call vafilt,$(DPKG_VARS),DEB_BUILD_ARCH) +DEB_BUILD_GNU_TYPE ?= $(call vafilt,$(DPKG_VARS),DEB_BUILD_GNU_TYPE) +DEB_HOST_ARCH ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH) +DEB_HOST_ARCH_BITS ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH_BITS) +DEB_HOST_ARCH_ENDIAN ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH_ENDIAN) +DEB_HOST_ARCH_OS ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH_OS) +DEB_HOST_GNU_TYPE ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_GNU_TYPE) +DEB_HOST_MULTIARCH ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_MULTIARCH) + +changelog_values := $(shell dpkg-parsechangelog \ + | awk '/^(Version|Source):/ {print $$2}') +PKGSOURCE := $(word 1, $(changelog_values)) +PKGVERSION := $(word 2, $(changelog_values)) + +LAST_CHANGE := $(shell dpkg-parsechangelog -S Date) +export BUILD_DATE := $(shell LC_ALL=C date -u +'%b %e %Y' -d '$(LAST_CHANGE)') +export BUILD_TIME := $(shell LC_ALL=C date -u +'%H:%M:%S' -d '$(LAST_CHANGE)') + +SPHINXOPTS := -D today='$(shell LC_ALL=C date -u +'%B %d, %Y' -d '$(LAST_CHANGE)')' +SPHINXOPTS += -D html_last_updated_fmt='$(shell LC_ALL=C date -u +'%B %d, %Y' -d '$(LAST_CHANGE)')' +export SPHINXOPTS + +on_buildd := $(shell [ -f /CurrentlyBuilding -o "$$LOGNAME" = buildd -o "$$USER" = buildd ] && echo yes) + +dh_compat2 := $(shell dpkg --compare-versions "$$(dpkg-query -f '$${Version}' -W debhelper)" lt 9.20150811ubuntu2 && echo DH_COMPAT=2) + +ifneq (,$(findstring nocheck, $(DEB_BUILD_OPTIONS))) + WITHOUT_CHECK := yes +endif +WITHOUT_BENCH := +ifneq (,$(findstring nobench, $(DEB_BUILD_OPTIONS))) + WITHOUT_BENCH := yes +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386)) + WITHOUT_BENCH := disabled on $(DEB_HOST_ARCH) +endif +ifeq ($(on_buildd),yes) + ifneq (,$(findstring $(DEB_HOST_ARCH), hppa mips mipsel mipsn32 mipsn32el mips64 mips64el mipsr6 mipsr6el mipsn32r6 mipsn32r6el mips64r6 mips64r6el s390)) + WITHOUT_CHECK := yes + endif +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386 kfreebsd-amd64 kfreebsd-i386)) + WITHOUT_CHECK := yes +endif +ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + WITHOUT_BENCH := yes + WITHOUT_CHECK := yes +endif + +COMMA = , +ifneq (,$(filter parallel=%,$(subst $(COMMA), ,$(DEB_BUILD_OPTIONS)))) + NJOBS := -j $(subst parallel=,,$(filter parallel=%,$(subst $(COMMA), ,$(DEB_BUILD_OPTIONS)))) +endif + +distribution := $(shell lsb_release -is) +distrelease := $(shell lsb_release -cs) +derivative := $(shell if dpkg-vendor --derives-from Ubuntu; then echo Ubuntu; \ + elif dpkg-vendor --derives-from Debian; then echo Debian; \ + else echo Unknown; fi) + +VER=2.7 +NVER=2.8 +PVER=python2.7 +PRIORITY=$(shell echo $(VER) | tr -d '.')0 + +PREVVER := $(shell awk '/^python/ && NR > 1 {print substr($$2,2,length($$2)-2); exit}' debian/changelog) + +# default versions are built from the python-defaults source package +# keep the definition to adjust package priorities. +DEFAULT_VERSION = yes +STATIC_PYTHON=yes + +MIN_MODS := $(shell awk '/^ / && $$2 == "module" { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_EXTS := $(shell awk '/^ / && $$2 ~ /^extension/ { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_BUILTINS := $(shell awk '/^ / && $$2 == "builtin" { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_PACKAGES := $(shell awk '/^ / && $$2 == "package" { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_ENCODINGS := $(foreach i, \ + $(filter-out \ + big5% bz2% cp932.py cp949.py cp950.py euc_% \ + gb% iso2022% johab.py shift_jis% , \ + $(shell cd Lib/encodings && echo *.py)), \ + encodings/$(i)) \ + codecs.py stringprep.py + +with_tk := no +with_gdbm := no +with_interp := static +#with_interp := shared + +PY_INTERPRETER = /usr/bin/python$(VER) + +ifeq ($(DEFAULT_VERSION),yes) + ifneq (,$(filter $(distrelease),lenny etch squeeze wheezy lucid precise trusty xenial yakkety)) + PY_PRIO = standard + else + PY_PRIO = optional + endif + #PYSTDDEP = , python (>= $(VER)) + PY_MINPRIO = $(PY_PRIO) +else + PY_PRIO = optional + PY_MINPRIO = $(PY_PRIO) +endif +ifneq (,$(filter $(distrelease),stretch lenny squeeze wheezy precise xenial yakkety zesty)) + with_fpectl = yes +endif + +ifeq (,$(filter $(distrelease),lenny etch squeeze wheezy lucid maverick natty oneiric)) + bd_qual = :any +endif +ifeq (,$(filter $(distrelease),lenny etch squeeze wheezy lucid maverick natty oneiric)) + ma_filter = cat +else + ma_filter = grep -v '^Multi-Arch:' +endif +ifneq (,$(filter $(distrelease),jessie experimental)) + bd_gcc = +endif +ifeq (,$(filter $(distrelease),lenny etch squeeze wheezy lucid maverick natty oneiric precise quantal raring saucy trusty)) + bd_dpkgdev = dpkg-dev (>= 1.17.11), +endif +ifeq (,$(filter $(distrelease),lenny etch squeeze wheezy lucid maverick natty oneiric precise quantal raring saucy trusty utopic vivid wily xenial)) + pf_bluetooth = $(EMPTY) +endif + +CC = $(DEB_HOST_GNU_TYPE)-gcc +CXX=$(DEB_HOST_GNU_TYPE)-g++ + +AR=$(DEB_HOST_GNU_TYPE)-ar +RANLIB=$(DEB_HOST_GNU_TYPE)-ranlib + +DPKG_CFLAGS := $(shell dpkg-buildflags --get CPPFLAGS; dpkg-buildflags --get CFLAGS) +DPKG_CFLAGS := $(subst -fstack-protector-strong,-fstack-protector,$(DPKG_CFLAGS)) +DPKG_LDFLAGS := $(shell dpkg-buildflags --get LDFLAGS) +OPT_CFLAGS := $(filter-out -O%,$(DPKG_CFLAGS)) # default is -O3 +DEBUG_CFLAGS := $(filter-out -D_FORTIFY_SOURCE=%,$(patsubst -O%,-O0,$(DPKG_CFLAGS))) + +# on alpha, use -O2 only, use -mieee +ifeq ($(DEB_HOST_ARCH),alpha) + OPT_CFLAGS += -mieee + DEBUG_CFLAGS += -mieee + EXTRA_OPT_FLAGS += -O2 +endif +# issues with ia64 and m68k with -O3 +ifeq ($(DEB_HOST_ARCH),m68k) + EXTRA_OPT_FLAGS += -O2 +endif + +ifneq (,$(filter $(DEB_HOST_ARCH), ppc64 ppc64el)) + OPT_CFLAGS += -fexceptions + DEBUG_CFLAGS += -fexceptions +endif + +ifeq ($(DEB_HOST_ARCH_OS),linux) + ifneq (,$(filter $(DEB_HOST_ARCH), amd64 arm64 armel armhf i386 powerpc ppc64 ppc64el s390x x32)) + with_pgo := yes + endif +endif +ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + with_pgo := +endif + +ifneq (,$(filter $(DEB_HOST_ARCH), amd64 arm64 armel armhf i386 powerpc ppc64 ppc64el s390x x32)) + with_lto := yes +endif + +ifeq ($(with_lto),yes) + LTO_CFLAGS = -g -flto -fuse-linker-plugin + with_fat_lto := $(shell dpkg --compare-versions $$($(CC) --version \ + | sed -n '/^$(CC)/s/.* //p') ge 4.9 && echo yes) + ifeq ($(with_fat_lto),yes) + LTO_CFLAGS += -ffat-lto-objects + endif + EXTRA_OPT_CFLAGS += $(LTO_CFLAGS) + AR=$(DEB_HOST_GNU_TYPE)-gcc-ar + RANLIB=$(DEB_HOST_GNU_TYPE)-gcc-ranlib +endif + +ifneq ($(with_fpectl),yes) + ifeq ($(derivative),Ubuntu) + arch_substvars = '-Vpyfpe:Breaks=$(shell tr '\n' ' ' < debian/pyfpe-breaks.$(derivative))' + else ifeq ($(derivative),Debian) + arch_substvars = '-Vpyfpe:Breaks=$(shell tr '\n' ' ' < debian/pyfpe-breaks.$(derivative))' + endif +endif + +make_build_target = $(if $(with_pgo),profile-opt) + +buildd_static := $(CURDIR)/build-static +buildd_shared := $(CURDIR)/build-shared +buildd_debug := $(CURDIR)/build-debug +buildd_shdebug := $(CURDIR)/build-shdebug + +d := debian/tmp +scriptdir = usr/share/lib/python$(VER) +scriptdir = usr/share/python$(VER) +scriptdir = usr/lib/python$(VER) + +# package names and directories +p_base := $(PVER) +p_min := $(PVER)-minimal +p_lib := lib$(PVER) +p_tk := $(PVER)-tk +p_gdbm := $(PVER)-gdbm +p_dev := $(PVER)-dev +p_exam := $(PVER)-examples +p_idle := idle-$(PVER) +p_doc := $(PVER)-doc +p_dbg := $(PVER)-dbg + +p_lbase := lib$(PVER)-stdlib +p_lmin := lib$(PVER)-minimal +p_ldev := lib$(PVER)-dev +p_ldbg := lib$(PVER)-dbg +p_ltst := lib$(PVER)-testsuite + +d_base := debian/$(p_base) +d_min := debian/$(p_min) +d_lib := debian/$(p_lib) +d_tk := debian/$(p_tk) +d_gdbm := debian/$(p_gdbm) +d_dev := debian/$(p_dev) +d_exam := debian/$(p_exam) +d_idle := debian/$(p_idle) +d_doc := debian/$(p_doc) +d_dbg := debian/$(p_dbg) + +d_lbase := debian/$(p_lbase) +d_lmin := debian/$(p_lmin) +d_ldev := debian/$(p_ldev) +d_ldbg := debian/$(p_ldbg) +d_ltst := debian/$(p_ltst) + +build-arch: stamps/stamp-build +build-indep: stamps/stamp-build-doc +build: build-arch +stamps/stamp-build: stamps/stamp-build-static stamps/stamp-mincheck \ + stamps/stamp-build-shared stamps/stamp-build-debug \ + stamps/stamp-build-shared-debug \ + stamps/stamp-check stamps/stamp-pystone stamps/stamp-pybench + touch $@ + +PROFILE_EXCLUDES = test_compiler test_distutils test_platform test_subprocess \ + test_multiprocessing test_cprofile \ + test_thread test_threaded_import test_threadedtempfile \ + test_socketserver \ + test_threading test_threading_local test_threadsignals \ + test_dbm_dumb test_dbm_ndbm test_pydoc test_sundry test_gdb \ + +ifneq (,$(filter $(DEB_HOST_ARCH), arm armel)) + PROFILE_EXCLUDES += test_float +endif +ifneq (,$(filter $(DEB_HOST_ARCH), sparc kfreebsd-amd64 kfreebsd-i386)) + PROFILE_EXCLUDES += test_io +endif +PROFILE_EXCLUDES += test_zipfile +PROFILE_EXCLUDES += test_xmlrpc +PROFILE_EXCLUDES += test_bsddb3 + +PROFILE_TASK = ../Lib/test/regrtest.py \ + -x $(sort $(TEST_EXCLUDES) $(PROFILE_EXCLUDES)) + +stamps/stamp-build-static: stamps/stamp-configure-static + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_static) \ + EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" \ + PROFILE_TASK='$(PROFILE_TASK)' $(make_build_target) + + : # check that things are correctly built +ifeq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + ifneq (,$(filter $(DEB_HOST_ARCH_OS), linux)) + cd $(buildd_static) && ./python -c 'from _multiprocessing import SemLock' + endif +endif + + touch stamps/stamp-build-static + +stamps/stamp-build-shared: stamps/stamp-configure-shared + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_shared) \ + EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" +# : # build the shared library +# $(MAKE) $(NJOBS) -C $(buildd_shared) \ +# libpython$(VER).so + : # build a static library with PIC objects + $(MAKE) $(NJOBS) -C $(buildd_shared) \ + EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" \ + LIBRARY=libpython$(VER)-pic.a libpython$(VER)-pic.a + touch stamps/stamp-build-shared + +stamps/stamp-build-debug: stamps/stamp-configure-debug + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_debug) \ + EXTRA_CFLAGS="$(DEBUG_CFLAGS)" + touch stamps/stamp-build-debug + +stamps/stamp-build-shared-debug: stamps/stamp-configure-shared-debug + dh_testdir + : # build the shared debug library + $(MAKE) $(NJOBS) -C $(buildd_shdebug) \ + EXTRA_CFLAGS="$(DEBUG_CFLAGS)" + touch stamps/stamp-build-shared-debug + +common_configure_args = \ + --prefix=/usr \ + --enable-ipv6 \ + --enable-unicode=ucs4 \ + --with-dbmliborder=bdb:gdbm \ + --with-system-expat \ + --with-computed-gotos + +ifneq (,$(filter $(DEB_HOST_ARCH), avr32 or1k)) + common_configure_args += --without-ffi +else + common_configure_args += --with-system-ffi +endif + +ifeq ($(with_fpectl),yes) + common_configure_args += \ + --with-fpectl +endif + +ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + common_configure_args += --host=$(DEB_HOST_GNU_TYPE) --build=$(DEB_BUILD_GNU_TYPE) + config_site = ac_cv_file__dev_ptmx=yes ac_cv_file__dev_ptc=yes + ifeq (,$(filter $(DEB_HOST_ARCH),arm m68k)) + ifeq ($(DEB_HOST_ARCH_ENDIAN),little) + config_site += ac_cv_little_endian_double=yes + else + config_site += ac_cv_big_endian_double=yes + endif + endif +endif + +stamps/stamp-configure-shared: stamps/stamp-patch + rm -rf $(buildd_shared) + mkdir -p $(buildd_shared) + cd $(buildd_shared) && \ + CC="$(CC)" CXX="$(CXX)" AR="$(AR)" RANLIB="$(RANLIB)" \ + CFLAGS="$(OPT_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + $(config_site) \ + ../configure \ + --enable-shared \ + $(common_configure_args) + + $(call __post_configure,$(buildd_shared)) + + touch stamps/stamp-configure-shared + +stamps/stamp-configure-static: stamps/stamp-patch + rm -rf $(buildd_static) + mkdir -p $(buildd_static) + cd $(buildd_static) && \ + CC="$(CC)" CXX="$(CXX)" AR="$(AR)" RANLIB="$(RANLIB)" \ + CFLAGS="$(OPT_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + $(config_site) \ + ../configure \ + $(common_configure_args) + + $(call __post_configure,$(buildd_static)) + + touch stamps/stamp-configure-static + +stamps/stamp-configure-debug: stamps/stamp-patch + rm -rf $(buildd_debug) + mkdir -p $(buildd_debug) + cd $(buildd_debug) && \ + CC="$(CC)" CXX="$(CXX)" AR="$(AR)" RANLIB="$(RANLIB)" \ + CFLAGS="$(DEBUG_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + $(config_site) \ + ../configure \ + $(common_configure_args) \ + --with-pydebug + + $(call __post_configure,$(buildd_debug)) + + touch stamps/stamp-configure-debug + +stamps/stamp-configure-shared-debug: stamps/stamp-patch + rm -rf $(buildd_shdebug) + mkdir -p $(buildd_shdebug) + cd $(buildd_shdebug) && \ + CC="$(CC)" CXX="$(CXX)" AR="$(AR)" RANLIB="$(RANLIB)" \ + CFLAGS="$(DEBUG_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + $(config_site) \ + ../configure \ + $(common_configure_args) \ + --enable-shared \ + --with-pydebug + + $(call __post_configure,$(buildd_shdebug)) + + touch stamps/stamp-configure-shared-debug + +define __post_configure + egrep \ + "^#($$(awk -v ORS='|' '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in)XX)" \ + Modules/Setup.dist \ + | sed -e 's/^#//' -e 's/-Wl,-Bdynamic//;s/-Wl,-Bstatic//' \ + >> $(1)/Modules/Setup.local + + : # unconditionally run makesetup + cd $(1) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + mv $(1)/config.c $(1)/Modules/ + + : # and fix the timestamps + $(MAKE) -C $(1) Makefile Modules/config.c + + : # apply workaround for missing os.fsync + sed 's/HAVE_SYNC/HAVE_FSYNC/g' $(1)/pyconfig.h \ + > $(1)/pyconfig.h.new + touch -r $(1)/pyconfig.h $(1)/pyconfig.h.new + mv -f $(1)/pyconfig.h.new $(1)/pyconfig.h + + : # this second rule doesn't build with -fPIC, remove it for shared builds. + $(if $(findstring build-sh,$(1)), \ + sed '/^Modules\/_math.o: .*PY_CORE_CFLAGS/d' $(1)/Makefile > $(1)/Makefile.fixed; \ + touch -r $(1)/Makefile $(1)/Makefile.fixed; \ + mv -f $(1)/Makefile.fixed $(1)/Makefile \ + ) +endef + +stamps/stamp-mincheck: stamps/stamp-build-static debian/PVER-minimal.README.Debian.in +ifeq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + for m in $(MIN_MODS) $(MIN_PACKAGES) $(MIN_EXTS) $(MIN_BUILTINS); do \ + echo "import $$m"; \ + done > $(buildd_static)/minmods.py + cd $(buildd_static) && ./python ../debian/pymindeps.py minmods.py \ + > $(buildd_static)/mindeps.txt + if [ -x /usr/bin/dot ]; then \ + cd $(buildd_static); \ + ./python ../debian/depgraph.py < mindeps.txt > mindeps.dot; \ + dot -Tpng -o $(buildd_static)/mindeps.png \ + $(buildd_static)/mindeps.dot; \ + else true; fi + cd $(buildd_static) && ./python ../debian/mincheck.py \ + minmods.py mindeps.txt +endif + touch stamps/stamp-mincheck + +TEST_RESOURCES = all +ifeq ($(on_buildd),yes) + TEST_RESOURCES := $(TEST_RESOURCES),-network,-urlfetch,-bsddb +endif +TESTOPTS = -w -l -u$(TEST_RESOURCES) +#TESTOPTS = -v -l -u$(TEST_RESOURCES) +TEST_EXCLUDES = +ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_codecmaps_cn test_codecmaps_hk \ + test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw \ + test_normalization test_ossaudiodev + ifneq (,$(filter $(DEB_HOST_ARCH), mips mipsel powerpc kfreebsd-i386 sparc)) + TEST_EXCLUDES += test_threading + endif + ifeq (,$(wildcard $(HOME))) + TEST_EXCLUDES += test_site + endif +endif +ifeq (,$(wildcard /dev/dsp)) + TEST_EXCLUDES += test_linuxaudiodev test_ossaudiodev +endif +ifneq (,$(filter $(DEB_HOST_ARCH), armel hppa powerpc)) + TEST_EXCLUDES += test_multiprocessing +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hppa)) + TEST_EXCLUDES += test_fork1 test_socketserver test_threading test_wait3 test_wait4 test_gdb +endif +ifneq (,$(filter $(DEB_HOST_ARCH), arm avr32)) + TEST_EXCLUDES += test_ctypes +endif +TEST_EXCLUDES += test_bsddb3 +TEST_EXCLUDES += test_ensurepip +ifneq (,$(filter $(DEB_HOST_ARCH), arm armel avr32 m68k)) + ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_compiler + endif +endif +TEST_EXCLUDES += test_gdb +# fails on some buildds +ifneq (,$(filter $(DEB_HOST_ARCH), amd64 armel armhf mips mipsel sparc)) + TEST_EXCLUDES += test_io +endif +ifneq (,$(filter $(DEB_HOST_ARCH), alpha)) + TEST_EXCLUDES += test_signal +endif +ifneq (,$(filter $(DEB_HOST_ARCH), kfreebsd-amd64 kfreebsd-i386)) + TEST_EXCLUDES += test_io test_signal +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386)) + TEST_EXCLUDES += test_io test_random test_signal test_socket test_socketserver test_ssl \ + test_threading test_subprocess +endif +ifneq (,$(filter $(DEB_HOST_ARCH), ia64)) + TEST_EXCLUDES += test_threading test_subprocess +endif +# see http://bugs.python.org/issue25698 +TEST_EXCLUDES += test_cpickle +ifneq (,$(TEST_EXCLUDES)) + TESTOPTS += -x $(sort $(TEST_EXCLUDES)) + ifneq (,$(filter $(DEB_HOST_ARCH), mips mipsel)) + TESTOPTS_DEBUG := $(TESTOPTS) + else + TESTOPTS_DEBUG := $(filter-out test_gdb,$(TESTOPTS)) + endif +endif + +ifneq (,$(wildcard /usr/bin/localedef)) + SET_LOCPATH = LOCPATH=$(CURDIR)/locales +endif + +stamps/stamp-check: +ifeq ($(WITHOUT_CHECK),yes) + echo "check run disabled for this build" > $(buildd_static)/test_results +else + : # build locales needed by the testsuite + rm -rf locales + mkdir locales + if which localedef >/dev/null 2>&1; then \ + sh debian/locale-gen; \ + fi + + @echo ========== test environment ============ + @env + @echo ======================================== + ifeq (,$(findstring $(DEB_HOST_ARCH), alpha)) + ( \ + echo '#! /bin/sh'; \ + echo 'set -x'; \ + echo 'export TERM=$${TERM:-dumb}'; \ + echo '$(buildd_static)/python $(CURDIR)/debian/script.py test_results '\''make test TESTOPTS="$(TESTOPTS_DEBUG)"'\'; \ + echo 'echo DONE'; \ + ) > $(buildd_debug)/run_tests + chmod 755 $(buildd_debug)/run_tests + @echo "BEGIN test debug" + -tmphome=$$(mktemp -d); export HOME=$$tmphome; \ + cd $(buildd_debug) && time xvfb-run -a -e xvfb-run.log ./run_tests; \ + rm -rf $$tmphome + @echo "END test debug" + endif + + ( \ + echo '#! /bin/sh'; \ + echo 'set -x'; \ + echo 'export TERM=$${TERM:-dumb}'; \ + echo 'export $(SET_LOCPATH)'; \ + echo '$(buildd_static)/python $(CURDIR)/debian/script.py test_results '\''make test EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" TESTOPTS="$(TESTOPTS)"'\'; \ + echo 'echo DONE'; \ + ) > $(buildd_static)/run_tests + chmod 755 $(buildd_static)/run_tests + @echo "BEGIN test static" + -tmphome=$$(mktemp -d); export HOME=$$tmphome; \ + cd $(buildd_static) && time xvfb-run -a -e xvfb-run.log ./run_tests; \ + rm -rf $$tmphome + @echo "END test static" + + ( \ + echo '#! /bin/sh'; \ + echo 'set -x'; \ + echo 'export TERM=$${TERM:-dumb}'; \ + echo 'export $(SET_LOCPATH)'; \ + echo '$(buildd_static)/python $(CURDIR)/debian/script.py test_results '\''make test EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" TESTOPTS="$(TESTOPTS)"'\'; \ + echo 'echo DONE'; \ + ) > $(buildd_shared)/run_tests + chmod 755 $(buildd_shared)/run_tests + @echo "BEGIN test shared" + -tmphome=$$(mktemp -d); export HOME=$$tmphome; \ + cd $(buildd_shared) && time xvfb-run -a -e xvfb-run.log ./run_tests; \ + rm -rf $$tmphome + @echo "END test shared" +endif + cp -p $(buildd_static)/test_results debian/ + touch stamps/stamp-check + +stamps/stamp-pystone: +ifeq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + @echo "BEGIN pystone static" + cd $(buildd_static) && ./python ../Lib/test/pystone.py + cd $(buildd_static) && ./python ../Lib/test/pystone.py + @echo "END pystone static" + @echo "BEGIN pystone shared" + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Lib/test/pystone.py + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Lib/test/pystone.py + @echo "END pystone shared" + @echo "BEGIN pystone debug" + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + @echo "END pystone debug" +endif + touch stamps/stamp-pystone + +#ifeq (,$(filter $(DEB_HOST_ARCH), arm armel avr32 hppa mips mipsel m68k)) + pybench_options = -C 2 -n 5 -w 4 +#endif + +stamps/stamp-pybench: +ifeq ($(WITHOUT_BENCH),yes) + echo "pybench run disabled for this build" > $(buildd_static)/pybench.log +else + @echo "BEGIN pybench static" + cd $(buildd_static) \ + && time ./python ../Tools/pybench/pybench.py -f run1.pybench $(pybench_options) + cd $(buildd_static) \ + && ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench $(pybench_options) + @echo "END pybench static" + @echo "BEGIN pybench shared" + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. \ + ./python ../Tools/pybench/pybench.py -f run1.pybench $(pybench_options) + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. \ + ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench $(pybench_options) + @echo "END pybench shared" + @echo "BEGIN shared/static comparision" + $(buildd_static)/python Tools/pybench/pybench.py \ + -s $(buildd_static)/run2.pybench -c $(buildd_shared)/run2.pybench \ + | tee $(buildd_static)/pybench.log + @echo "END shared/static comparision" +endif + touch stamps/stamp-pybench + +minimal-test: + rm -rf mintest + mkdir -p mintest/lib mintest/dynlib mintest/testlib mintest/all-lib + cp -p $(buildd_static)/python mintest/ + cp -p $(foreach i,$(MIN_MODS),Lib/$(i).py) \ + mintest/lib/ + cp -a $(foreach i,$(MIN_PACKAGES),Lib/$(i)) \ + mintest/lib/ + cp -p $(wildcard $(foreach i,$(MIN_EXTS),$(buildd_static)/build/lib*/$(i).*.so)) \ + mintest/dynlib/ + cp -p Lib/unittest.py mintest/lib/ + cp -pr Lib/test mintest/lib/ + cp -pr Lib mintest/all-lib + cp -p $(buildd_static)/build/lib*/*.so mintest/all-lib/ + ( \ + echo "import sys"; \ + echo "sys.path = ["; \ + echo " '$(CURDIR)/mintest/lib',"; \ + echo " '$(CURDIR)/mintest/dynlib',"; \ + echo "]"; \ + cat Lib/test/regrtest.py; \ + ) > mintest/lib/test/mintest.py + cd mintest && ./python -E -S lib/test/mintest.py \ + -x test_codecencodings_cn test_codecencodings_hk \ + test_codecencodings_jp test_codecencodings_kr \ + test_codecencodings_tw test_codecs test_multibytecodec \ + +stamps/stamp-doc-html: + dh_testdir + $(MAKE) -C Doc html + @mkdir -p stamps + touch stamps/stamp-doc-html + +build-doc: stamps/stamp-patch stamps/stamp-build-doc +stamps/stamp-build-doc: stamps/stamp-doc-html + touch stamps/stamp-build-doc + +control-file: + sed -e "s/@PVER@/$(PVER)/g" \ + -e "s/@VER@/$(VER)/g" \ + -e "s/@PYSTDDEP@/$(PYSTDDEP)/g" \ + -e "s/@PRIO@/$(PY_PRIO)/g" \ + -e "s/@MINPRIO@/$(PY_MINPRIO)/g" \ + -e "s/@bd_qual@/$(bd_qual)/g" \ + -e "s/@bd_gcc@/$(bd_gcc)/g" \ + -e "s/@bd_dpkgdev@/$(bd_dpkgdev)/g" \ + -e "s/@pf_bluetooth@/$(pf_bluetooth)/g" \ + debian/control.in \ + | $(ma_filter) \ + > debian/control.tmp +ifeq ($(derivative),Ubuntu) + ifneq (,$(findstring ubuntu, $(PKGVERSION))) + m='Ubuntu Core Developers '; \ + sed -i "/^Maintainer:/s/\(.*\)/Maintainer: $$m\nXSBC-Original-\1/" \ + debian/control.tmp + endif +endif + [ -e debian/control ] \ + && cmp -s debian/control debian/control.tmp \ + && rm -f debian/control.tmp && exit 0; \ + mv debian/control.tmp debian/control + + + +clean: control-file + dh_testdir + dh_testroot + dh_autotools-dev_restoreconfig + $(MAKE) -f debian/rules unpatch + rm -rf stamps .pc + rm -f debian/test_results + + $(MAKE) -C Doc clean + sed 's/^@/#/' Makefile.pre.in | $(MAKE) -f - srcdir=. distclean + rm -rf Lib/test/db_home + rm -rf $(buildd_static) $(buildd_shared) $(buildd_debug) $(buildd_shdebug) + find -name '*.py[co]' | xargs -r rm -f + rm -f Lib/lib2to3/*.pickle + rm -rf Lib/plat-$(DEB_HOST_MULTIARCH) + rm -rf locales + rm -rf $(d)-dbg $(d)-shdbg + + for f in debian/*.in; do \ + f2=`echo $$f | sed "s,PVER,$(PVER),g;s/@VER@/$(VER)/g;s,\.in$$,,"`; \ + if [ $$f2 != debian/control ] && [ $$f2 != debian/source.lintian-overrides ]; then \ + rm -f $$f2; \ + fi; \ + done + dh_clean + +stamps/stamp-control: + : # We have to prepare the various control files + + for f in debian/*.in; do \ + f2=`echo $$f | sed "s,PVER,$(PVER),g;s/@VER@/$(VER)/g;s,\.in$$,,"`; \ + if [ $$f2 != debian/control ]; then \ + sed -e "s/@PVER@/$(PVER)/g;s/@VER@/$(VER)/g" \ + -e "s/@PRIORITY@/$(PRIORITY)/g" \ + -e "s,@SCRIPTDIR@,/$(scriptdir),g" \ + -e "s,@INFO@,$(info_docs),g" \ + -e "s,@HOST_QUAL@,:$(DEB_HOST_ARCH),g" \ + <$$f >$$f2; \ + fi; \ + done +ifeq ($(DEB_HOST_ARCH_BITS),64) + sed -i 's/\(Py_InitModule4[^@]*\)@/\1_64@/' \ + debian/lib$(PVER).symbols debian/lib$(PVER)-dbg.symbols +endif + +2to3-man: + help2man --no-info --version-string=$(VER) --no-discard-stderr \ + --name 'Python2 to Python3 converter' \ + 2to3-$(VER) > debian/2to3-$(VER).1 + +install: build-arch stamps/stamp-install +stamps/stamp-install: stamps/stamp-build control-file stamps/stamp-control + dh_testdir + dh_testroot + dh_prep + dh_installdirs + + : # make install into tmp and subsequently move the files into + : # their packages' directories. + install -d $(d)/usr +ifeq ($(with_interp),static) + $(MAKE) -C $(buildd_static) install DESTDIR=$(CURDIR)/$(d) +else + $(MAKE) -C $(buildd_shared) install DESTDIR=$(CURDIR)/$(d) +endif + mkdir -p $(d)/usr/include/$(DEB_HOST_MULTIARCH)/$(PVER) + mv $(d)/usr/include/$(PVER)/pyconfig.h \ + $(d)/usr/include/$(DEB_HOST_MULTIARCH)/$(PVER)/. + mv $(d)/usr/bin/python-config.sh $(d)/usr/bin/python$(VER)-config + sed -i \ + -e 's/-O3/-O2/g;s/$(LTO_CFLAGS)//g' \ + -e 's/-fprofile-use *-fprofile-correction//g' \ + -e 's/-fstack-protector /-fstack-protector-strong /g' \ + $(d)/usr/bin/python$(VER)-config + + : # fiddle around with the platform directory + mkdir -p $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/ + set -x; echo XXXXXX; \ + for i in Lib/plat-linux2/*; do \ + n=$$(basename $$i); \ + if [ ! -f $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/$$n ]; then \ + cp -p $$i $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/; \ + fi; \ + done + rm -f $(d)/$(scriptdir)/lib-dynload/*.py + cp -p $(buildd_shared)/$(shell cat $(buildd_shared)/pybuilddir.txt)/_sysconfigdata.py \ + $(d)/$(scriptdir)/. + mv $(d)/$(scriptdir)/_sysconfigdata.py \ + $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/_sysconfigdata_nd.py + sed -i \ + -e 's/-O3/-O2/g;s/$(LTO_CFLAGS)//g' \ + -e 's/-fprofile-use *-fprofile-correction//g' \ + -e 's/-fstack-protector /-fstack-protector-strong /g' \ + $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/_sysconfigdata_nd.py + cp -p debian/_sysconfigdata.py $(d)/$(scriptdir) + + -find $(d)/usr/lib/python$(VER) -name '*_failed*.so' + find $(d)/usr/lib/python$(VER) -name '*_failed*.so' | xargs -r rm -f + + test -f $(d)/usr/lib/python$(VER)/lib-dynload/_bsddb.so + + for i in $(d)/$(scriptdir)/lib-dynload/*.so; do \ + b=$$(basename $$i .so); \ + d=$${b}.$(DEB_HOST_MULTIARCH).so; \ + mv $$i $(d)/$(scriptdir)/lib-dynload/$$d; \ + done + + mv $(d)/usr/lib/libpython*.a $(d)/usr/lib/$(DEB_HOST_MULTIARCH)/ + + mv $(d)/usr/lib/python$(VER)/site-packages \ + $(d)/usr/lib/python$(VER)/dist-packages + + : # remove files, which are not packaged + rm -f $(d)/usr/bin/smtpd.py + rm -rf $(d)/usr/lib/python$(VER)/ctypes/macholib + rm -f $(d)/$(scriptdir)/plat-*/regen + rm -f $(d)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python.pc + rm -f $(d)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python2.pc + rm -f $(d)/usr/bin/python2{,-config} + rm -f $(d)/usr/share/man/man1/python.1 + rm -f $(d)/usr/share/man/man1/python2{,-config}.1 + rm -f $(d)/$(scriptdir)/lib2to3/*.pickle + + if [ -d $(d)/$(scriptdir)/ensurepip/_bundled ]; then \ + echo "don't ship the prebuilt ensurepip/_bundled wheels."; \ + rm -rf $(d)/$(scriptdir)/ensurepip/_bundled; \ + fi + + : # cannot build it, zlib maintainer won't provide a mingw build + find $(d) -name 'wininst*.exe' | xargs -r rm -f + + : # fix some file permissions + chmod a-x $(d)/$(scriptdir)/{fractions,lib-tk/Tix}.py + + : # move manpages to new names + if [ -d $(d)/usr/man/man1 ]; then \ + mkdir -p $(d)/usr/share/man; \ + mv $(d)/usr/man/man1/* $(d)/usr/share/man/man1/; \ + rm -rf $(d)/usr/man/; \ + fi + cp -p debian/pydoc.1 $(d)/usr/share/man/man1/pydoc$(VER).1 + + : # Symlinks to /usr/bin for some tools + ln -sf ../lib/python$(VER)/pdb.py $(d)/usr/bin/pdb$(VER) + cp -p debian/pdb.1 $(d)/usr/share/man/man1/pdb$(VER).1 + + : # versioned install only + rm -f $(d)/usr/bin/python-config + + mv $(d)/usr/bin/2to3 $(d)/usr/bin/2to3-$(VER) + cp debian/2to3-$(VER).1 $(d)/usr/share/man/man1/2to3-$(VER).1 + +# : # remove the bsddb stuff +# rm -rf $(d)/$(scriptdir)/bsddb +# rm -f $(d)/$(scriptdir)/lib-dynload/_bsddb.so + + : # Remove version information from the egg-info file + mv $(d)/$(scriptdir)/lib-dynload/Python-$(VER)*.egg-info \ + $(d)/$(scriptdir)/lib-dynload/Python-$(VER).egg-info + + dh_installdirs -p$(p_lib) \ + usr/lib/$(DEB_HOST_MULTIARCH) \ + $(scriptdir)/config-$(DEB_HOST_MULTIARCH) \ + usr/share/doc + : # install the shared library + cp -p $(buildd_shared)/libpython$(VER).so.1.0 \ + $(d_lib)/usr/lib/$(DEB_HOST_MULTIARCH)/ + dh_link -p$(p_lib) \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).so.1.0 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).so.1 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).so.1 \ + /$(scriptdir)/config-$(DEB_HOST_MULTIARCH)/libpython$(VER).so + + ln -sf $(p_base) $(d_lib)/usr/share/doc/$(p_lib) + + ln -sf libpython$(VER).so.1 $(d)/usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).so + +ifeq ($(with_interp),shared) + : # install the statically linked runtime + install -m755 $(buildd_static)/python $(d)/usr/bin/python$(VER)-static +endif + + mv $(d)/usr/bin/pydoc $(d)/usr/bin/pydoc$(VER) + cp -p Tools/i18n/pygettext.py $(d)/usr/bin/pygettext$(VER) + cp -p debian/pygettext.1 $(d)/usr/share/man/man1/pygettext$(VER).1 + + : # install the Makefile of the shared python build + sed -e '/^OPT/s,-O3,-O2,' \ + -e 's/$(LTO_CFLAGS)//g' \ + -e 's/-fstack-protector /-fstack-protector-strong /g' \ + -e 's,^RUNSHARED *=.*,RUNSHARED=,' \ + -e '/BLDLIBRARY/s/-L\. //' \ + build-shared/Makefile > $(d)/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)/Makefile + + : # Move the binary and the minimal libraries into $(p_lmin). + dh_installdirs -p$(p_lmin) \ + etc/$(PVER) \ + usr/bin \ + usr/include/$(PVER) \ + usr/share/man/man1 \ + $(scriptdir)/lib-dynload + $(dh_compat2) dh_movefiles -p$(p_lmin) --sourcedir=$(d) \ + $(foreach i,$(MIN_MODS),$(scriptdir)/$(i).py) \ + $(foreach i,$(MIN_PACKAGES),$(scriptdir)/$(i)) \ + $(foreach i,$(MIN_ENCODINGS),$(scriptdir)/$(i)) \ + /$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/_sysconfigdata_nd.py \ + $(scriptdir)/site.py \ + $(shell cd $(d); for i in $(MIN_EXTS); do \ + test -e $(scriptdir)/lib-dynload/$$i.so \ + && echo $(scriptdir)/lib-dynload/$$i.so; \ + done; true) + + : # Move the binary and the minimal libraries into $(p_min). + dh_installdirs -p$(p_min) \ + usr/bin \ + usr/share/man/man1 + $(dh_compat2) dh_movefiles -p$(p_min) --sourcedir=$(d) \ + usr/bin/python$(VER) \ + usr/share/man/man1/python$(VER).1 + + : # Install sitecustomize.py. + cp -p debian/sitecustomize.py $(d_lmin)/etc/$(PVER)/ + dh_link -p$(p_lmin) /etc/$(PVER)/sitecustomize.py \ + /$(scriptdir)/sitecustomize.py + + : # Move the static library and the header files into $(p_ldev). +# mv $(d)/usr/share/include/python$(VER)/* $(d)/usr/include/python$(VER)/. +# rm -rf $(d)/usr/share/include + + cp $(d)/usr/bin/python$(VER)-config $(d)/usr/bin/$(DEB_HOST_MULTIARCH)-python$(VER)-config + dh_installdirs -p$(p_ldev) \ + usr/bin \ + $(scriptdir) \ + usr/include \ + usr/share/man/man1 + + $(dh_compat2) dh_movefiles -p$(p_ldev) --sourcedir=$(d) \ + usr/bin/$(DEB_HOST_MULTIARCH)-python$(VER)-config \ + usr/lib/python$(VER)/config-$(DEB_HOST_MULTIARCH) \ + usr/include \ + usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).{a,so} \ + usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python-$(VER)*.pc + + sed 's/@subdir@/$(PVER)/;s/@header@/pyconfig.h/' \ + debian/multiarch.h.in > $(d_ldev)/usr/include/$(PVER)/pyconfig.h + + cp -p debian/python-config.1 \ + $(d_ldev)/usr/share/man/man1/$(DEB_HOST_MULTIARCH)-python$(VER)-config.1 + +ifneq ($(DEB_HOST_MULTIARCH),$(DEB_HOST_GNU_TYPE)) + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config \ + $(d_ldev)/usr/bin/$(DEB_HOST_GNU_TYPE)-$(PVER)-config + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config.1.gz \ + $(d_ldev)/usr/share/man/man1/$(DEB_HOST_GNU_TYPE)-$(PVER)-config.1.gz +endif + + sed -i \ + -e '/^Cflags:/s,$$, -I$${includedir}/$(DEB_HOST_MULTIARCH)/python$(VER),' \ + -e '/^libdir=/d;s/-L\$${libdir} *//' \ + $(d_ldev)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python-$(VER).pc + + dh_link -p$(p_ldev) \ + /usr/lib/$(PVER)/config-$(DEB_HOST_MULTIARCH)/libpython$(VER).a \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).a + + cp -p $(buildd_shared)/libpython$(VER)-pic.a \ + $(d_ldev)/usr/lib/python$(VER)/config-$(DEB_HOST_MULTIARCH)/ + + : # Move the static library and the header files into $(p_dev). + dh_installdirs -p$(p_dev) \ + usr/share/doc/python$(VER)/$(DEB_HOST_MULTIARCH) \ + usr/share/man/man1 \ + $(scriptdir) \ + $(scriptdir)/doc/html + + cp -p Misc/HISTORY Misc/README.valgrind Misc/gdbinit \ + debian/README.maintainers \ + $(d_dev)/usr/share/doc/python$(VER)/ + cp -p debian/test_results $(buildd_static)/pybench.log \ + $(d_dev)/usr/share/doc/python$(VER)/$(DEB_HOST_MULTIARCH)/ + + $(dh_compat2) dh_movefiles -p$(p_dev) --sourcedir=$(d) \ + usr/bin/python$(VER)-config \ + usr/lib/python$(VER)/distutils/command/wininst-*.exe + + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config $(d_dev)/usr/bin/$(PVER)-config + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config.1.gz $(d_dev)/usr/share/man/man1/$(PVER)-config.1.gz + +ifeq ($(with_tk),yes) + : # Move the Tkinter files into $(p_tk). + dh_installdirs -p$(p_tk) \ + $(scriptdir) \ + usr/lib/python$(VER)/lib-dynload + $(dh_compat2) dh_movefiles -p$(p_tk) --sourcedir=$(d) \ + usr/lib/python$(VER)/lib-dynload/_tkinter.so +endif + +ifeq ($(with_gdbm),yes) + : # gdbm and dbm modules into $(p_gdbm). + dh_installdirs -p$(p_gdbm) \ + usr/lib/python$(VER)/lib-dynload + $(dh_compat2) dh_movefiles -p$(p_gdbm) --sourcedir=$(d) \ + usr/lib/python$(VER)/lib-dynload/gdbm.so +endif + + : # The test framework into $(p_lbase) + $(dh_compat2) dh_movefiles -p$(p_lbase) --sourcedir=$(d) \ + $(scriptdir)/test/support \ + $(scriptdir)/test/{regrtest.py,test_support.py,__init__.py,pystone.py} + + : # The complete testsuite into $(p_ltst) + $(dh_compat2) dh_movefiles -p$(p_ltst) --sourcedir=$(d) \ + $(scriptdir)/test \ + $(scriptdir)/ctypes/test \ + $(scriptdir)/bsddb/test \ + $(scriptdir)/email/test \ + $(scriptdir)/json/tests \ + $(scriptdir)/sqlite3/test \ + $(scriptdir)/distutils/tests \ + $(scriptdir)/lib2to3/tests \ + $(scriptdir)/unittest/test \ + $(scriptdir)/lib-tk/test + + : # test_ctypes fails with test_macholib.py installed + rm -f $(d_ltst)/$(scriptdir)/ctypes/test/test_macholib.py + : # test_bdist_wininst fails, '*.exe' files are not installed + rm -f $(d_ltst)/$(scriptdir)/distutils/tests/test_bdist_wininst.py + + : # IDLE + mv $(d)/usr/bin/idle $(d)/usr/bin/idle-python$(VER) + rm -f $(d)/usr/lib/python$(VER)/idlelib/idle.bat + dh_installdirs -p$(p_idle) \ + usr/bin \ + usr/share/man/man1 + $(dh_compat2) dh_movefiles -p$(p_idle) --sourcedir=$(d) \ + usr/lib/python$(VER)/idlelib \ + usr/bin/idle-python$(VER) + cp -p debian/idle-$(PVER).1 $(d_idle)/usr/share/man/man1/ + + : # Move the demos and tools into $(p_exam)'s doc directory + dh_installdirs -p$(p_exam) \ + usr/share/doc/python$(VER)/examples + + cp -rp Demo Tools $(d_exam)/usr/share/doc/python$(VER)/examples/ + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Demo/sgi + : # IDLE is in its own package: + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Tools/idle + : # XXX: We don't need rgb.txt, we'll use our own: + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Tools/pynche/X + + : # XXX: Some files in upstream Demo and Tools have strange + : # exec permissions, make lintian glad: + -chmod 644 $(d_tk)/$(scriptdir)/lib-tk/Tix.py + -chmod 644 $(d)/$(scriptdir)/runpy.py + + cd $(d_exam)/usr/share/doc/python$(VER)/examples && chmod 644 \ + Demo/{classes/*.py*,comparisons/patterns} \ + Demo/{rpc/test,threads/*.py*,md5test/*} \ + Demo/pdist/{client.py,cmdfw.py,cmptree.py,cvslib.py,cvslock.py,FSProxy.py,mac.py,rcsclient.py,rcslib.py,security.py,server.py,sumtree.py} \ + Demo/scripts/morse.py \ + Demo/sockets/{broadcast.py,ftp.py,mcast.py,radio.py} \ + Demo/tix/{bitmaps/{tix.gif,*x[pb]m*},samples/*.py} \ + Demo/tkinter/guido/{AttrDialog.py,hanoi.py,hello.py,imagedraw.py,imageview.py,listtree.py,ManPage.py,ShellWindow.py,wish.py} \ + Tools/scripts/pydocgui.pyw \ + Tools/scripts/mailerdaemon.py + rm -f $(d_exam)/usr/share/doc/python$(VER)/examples/Demo/scripts/newslist.* + + : # Replace all '#!' calls to python with $(PY_INTERPRETER) + : # and make them executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch'`; do \ + sed '1s,#!.*python[^ ]*\(.*\),#! $(PY_INTERPRETER)\1,' \ + $$i > $$i.temp; \ + if cmp --quiet $$i $$i.temp; then \ + rm -f $$i.temp; \ + else \ + mv -f $$i.temp $$i; \ + chmod 755 $$i; \ + echo "fixed interpreter: $$i"; \ + fi; \ + done + + : # Move the docs into $(p_base)'s /usr/share/doc/$(PVER) directory, + : # all other packages only have a copyright file. + dh_installdocs -p$(p_base) \ + README Misc/NEWS Misc/ACKS + ln -sf NEWS.gz $(d_base)/usr/share/doc/$(p_base)/changelog.gz + dh_installdocs --all -N$(p_base) -N$(p_dev) -N$(p_dbg) -N$(p_lib) debian/README.Debian + + : # IDLE has its own changelogs, docs... + dh_installchangelogs -p$(p_idle) Lib/idlelib/ChangeLog + dh_installdocs -p$(p_idle) Lib/idlelib/{NEWS,README,TODO,extend}.txt + + mkdir -p $(d_idle)/usr/share/applications + cp -p debian/idle.desktop \ + $(d_idle)/usr/share/applications/idle-$(PVER).desktop + + : # those packages have own README.Debian's + install -m 644 -p debian/README.$(p_base) \ + $(d_base)/usr/share/doc/$(PVER)/README.Debian + install -m 644 -p debian/README.$(p_idle) \ + $(d_idle)/usr/share/doc/$(p_idle)/README.Debian +ifeq ($(with_tk),yes) + cp -p debian/README.Tk $(d_tk)/usr/share/doc/$(p_tk)/ +endif + + : # library files into $(p_lbase) + dh_installdirs -p$(p_lbase) \ + usr/lib + dh_movefiles -p$(p_lbase) \ + usr/lib/python$(VER) + + : # The rest goes into $(p_base) + mkdir -p $(d)/usr/lib/python$(VER)/dist-packages + (cd $(d) && tar cf - .) | (cd $(d_base) && tar xpf -) + sh debian/dh_rmemptydirs -p$(p_base) + rm -f $(d_base)/usr/bin/python + + : # install egg-info for arparse + install -m 644 debian/argparse.egg-info $(d_lbase)/$(scriptdir)/ + + : # Install menu icon + dh_installdirs -p$(p_base) usr/share/pixmaps + cp -p debian/pylogo.xpm $(d_base)/usr/share/pixmaps/$(PVER).xpm + + : # generate binfmt file + mkdir -p $(d_min)/usr/share/binfmts +ifeq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + $(buildd_static)/python debian/mkbinfmt.py $(PVER) \ + > $(d_min)/usr/share/binfmts/$(PVER) +else + $(PVER) debian/mkbinfmt.py $(PVER) > $(d_min)/usr/share/binfmts/$(PVER) +endif + + : # desktop entry + mkdir -p $(d_base)/usr/share/applications + cp -p debian/$(PVER).desktop \ + $(d_base)/usr/share/applications/$(PVER).desktop + + : # remove some things + -find debian -name .cvsignore | xargs rm -f + -find debian -name '*.py[co]' | xargs rm -f + + : # remove empty directories, when all components are in place + -find debian ! -name lib-dynload -type d -empty -delete + + : # install debug package + rm -rf $(d)-dbg $(d)-shdbg + : # need some files from the shared build + $(MAKE) -C $(buildd_shdebug) install DESTDIR=$(CURDIR)/$(d)-shdbg + $(MAKE) -C $(buildd_debug) install DESTDIR=$(CURDIR)/$(d)-dbg + mv $(d)-dbg/usr/lib/libpython*.a $(d)-dbg/usr/lib/$(DEB_HOST_MULTIARCH)/ + mv $(d)-shdbg/$(scriptdir)/_sysconfigdata.py \ + $(d)-shdbg/$(scriptdir)/_sysconfigdata_d.py + + for i in $(d)-dbg/$(scriptdir)/lib-dynload/*_d.so; do \ + b=$$(basename $$i _d.so); \ + d=$${b}.$(DEB_HOST_MULTIARCH)_d.so; \ + mv $$i $(d)-dbg/$(scriptdir)/lib-dynload/$$d; \ + done + for i in $(d)-shdbg/$(scriptdir)/lib-dynload/*_d.so; do \ + b=$$(basename $$i _d.so); \ + d=$${b}.$(DEB_HOST_MULTIARCH)_d.so; \ + mv $$i $(d)-shdbg/$(scriptdir)/lib-dynload/$$d; \ + done + + dh_installdirs -p$(p_ldbg) \ + usr/bin \ + usr/share/man/man1 \ + $(scriptdir)/lib-dynload \ + $(scriptdir)/plat-$(DEB_HOST_MULTIARCH) \ + usr/include/$(PVER)_d \ + usr/include/$(DEB_HOST_MULTIARCH)/$(PVER)_d \ + usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig \ + + cp -p $(d)-shdbg/$(scriptdir)/lib-dynload/*.so \ + $(d_ldbg)/$(scriptdir)/lib-dynload/ + cp -p $(buildd_shdebug)/libpython$(VER)_d.so.1.0 \ + $(d_ldbg)/usr/lib/$(DEB_HOST_MULTIARCH)/ + dh_link -p$(p_ldbg) \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so.1.0 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so.1 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so.1 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so + sed -e '/^Libs:/s,-lpython$(VER),-lpython$(VER)_d,' \ + -e '/^Cflags:/s,python$(VER),python$(VER)_d,' \ + -e '/^Cflags:/s,$$, -I$${includedir}/$(DEB_HOST_MULTIARCH)/python$(VER)_d,' \ + -e '/^libdir=/d;s/-L\$${libdir} *//' \ + $(d)-dbg/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python-$(VER).pc \ + > $(d_ldbg)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python-$(VER)-dbg.pc + + : # in $(p_ldbg), prefix python-config with triplets + cp $(d)-shdbg/usr/bin/python-config.sh \ + $(d_ldbg)/usr/bin/$(DEB_HOST_MULTIARCH)-$(PVER)-dbg-config + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config.1.gz \ + $(d_ldbg)/usr/share/man/man1/$(DEB_HOST_MULTIARCH)-$(PVER)-dbg-config.1.gz +ifneq ($(DEB_HOST_MULTIARCH),$(DEB_HOST_GNU_TYPE)) + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-dbg-config \ + $(d_ldbg)/usr/bin/$(DEB_HOST_GNU_TYPE)-$(PVER)-dbg-config + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config.1.gz \ + $(d_ldbg)/usr/share/man/man1/$(DEB_HOST_GNU_TYPE)-$(PVER)-dbg-config.1.gz +endif + + dh_installdirs -p$(p_dbg) \ + usr/bin \ + $(scriptdir)/lib-dynload \ + usr/share/man/man1 \ + usr/share/doc/$(p_base) + + cp -p Misc/SpecialBuilds.txt $(d_dbg)/usr/share/doc/$(p_base)/ + cp -p debian/$(PVER)-dbg.README.Debian \ + $(d_dbg)/usr/share/doc/$(p_base)/README.debug + cp -p $(buildd_debug)/python $(d_dbg)/usr/bin/$(PVER)-dbg + cp -p $(d)-shdbg/usr/bin/python-config.sh \ + $(d_dbg)/usr/bin/$(PVER)-dbg-config +# cp -p $(buildd_debug)/build/lib*/*_d.so \ + $(d_dbg)/$(scriptdir)/lib-dynload/ + cp -p $(d)-shdbg/$(scriptdir)/_sysconfigdata_d.py \ + $(d_ldbg)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/ +ifneq ($(with_gdbm),yes) + rm -f $(d_ldbg)/$(scriptdir)/lib-dynload/gdbm.$(DEB_HOST_MULTIARCH)_d.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/gdbm.$(DEB_HOST_MULTIARCH).so +endif +ifneq ($(with_tk),yes) + rm -f $(d_ldbg)/$(scriptdir)/lib-dynload/_tkinter.$(DEB_HOST_MULTIARCH)_d.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/_tkinter.$(DEB_HOST_MULTIARCH).so +endif +# rm -f $(d_dbg)/$(scriptdir)/lib-dynload/_bsddb_d.so + + cp -a $(d)-dbg/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)_d \ + $(d_ldbg)/$(scriptdir)/ + ln -sf ../../$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so \ + $(d_ldbg)/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)_d/libpython$(VER)_d.so + ln -sf libpython$(VER)_d.so \ + $(d_ldbg)/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)_d/libpython$(VER).so + ln -sf libpython$(VER)_d.a \ + $(d_ldbg)/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)_d/libpython$(VER).a + + for i in $(d_ldev)/usr/include/$(PVER)/*; do \ + i=$$(basename $$i); \ + case $$i in pyconfig.h) continue; esac; \ + ln -sf ../$(PVER)/$$i $(d_ldbg)/usr/include/$(PVER)_d/$$i; \ + done + cp -p $(buildd_debug)/pyconfig.h $(d_ldbg)/usr/include/$(DEB_HOST_MULTIARCH)/$(PVER)_d/ + sed 's/@subdir@/$(PVER)_d/;s/@header@/pyconfig.h/' \ + debian/multiarch.h.in > $(d_ldbg)/usr/include/$(PVER)_d/pyconfig.h + ln -sf $(PVER).1.gz $(d_dbg)/usr/share/man/man1/$(PVER)-dbg.1.gz + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-dbg-config \ + $(d_dbg)/usr/bin/$(PVER)-dbg-config + ln -sf $(PVER)-config.1.gz $(d_dbg)/usr/share/man/man1/$(PVER)-dbg-config.1.gz + + for i in debian/*.overrides; do \ + b=$$(basename $$i .overrides); \ + install -D -m 644 $$i debian/$$b/usr/share/lintian/overrides/$$b; \ + done + + touch stamps/stamp-install + +# Build architecture-independent files here. +binary-indep: build-indep install stamps/stamp-control + dh_testdir -i + dh_testroot -i + + : # $(p_doc) package + dh_installdirs -p$(p_doc) \ + usr/share/doc/$(p_base) \ + usr/share/doc/$(p_doc) + dh_installdocs -p$(p_doc) + cp -a Doc/build/html $(d_doc)/usr/share/doc/$(p_base)/ + rm -f $(d_doc)/usr/share/doc/$(p_base)/html/_static/jquery.js + rm -f $(d_doc)/usr/share/doc/$(p_base)/html/_static/underscore.js + dh_link -p$(p_doc) \ + /usr/share/doc/$(p_base)/html \ + /usr/share/doc/$(p_doc)/html \ + /usr/share/javascript/jquery/jquery.js \ + /usr/share/doc/$(p_base)/html/_static/jquery.js \ + /usr/share/javascript/underscore/underscore.js \ + /usr/share/doc/$(p_base)/html/_static/underscore.js + + : # devhelp docs + $(buildd_static)/python debian/pyhtml2devhelp.py \ + $(d_doc)/usr/share/doc/$(p_base)/html index.html $(VER) \ + > $(d_doc)/usr/share/doc/$(p_base)/html/$(PVER).devhelp + gzip -9nv $(d_doc)/usr/share/doc/$(p_base)/html/$(PVER).devhelp + dh_link -p$(p_doc) \ + /usr/share/doc/$(p_base)/html /usr/share/devhelp/books/$(PVER) + + for i in $(p_ltst); do \ + rm -rf debian/$$i/usr/share/doc/$$i; \ + ln -s $(p_lbase) debian/$$i/usr/share/doc/$$i; \ + done + + dh_installdebconf -i $(dh_args) + dh_installexamples -i $(dh_args) + -dh_icons -i $(dh_args) || dh_iconcache -i $(dh_args) + dh_installchangelogs -i $(dh_args) + dh_link -i $(dh_args) + dh_compress -i $(dh_args) -X.py -X.cls -X.css -X.txt -X.json -X.js -Xobjects.inv -Xgdbinit + dh_fixperms -i $(dh_args) + + : # make python scripts starting with '#!' executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch' ! -perm 755`; do \ + if head -1 $$i | grep -q '^#!'; then \ + chmod 755 $$i; \ + echo "make executable: $$i"; \ + fi; \ + done + -find $(d_doc) -name '*.txt' -perm 755 -exec chmod 644 {} \; + + dh_installdeb -i $(dh_args) + dh_gencontrol -i $(dh_args) + dh_md5sums -i $(dh_args) + dh_builddeb -i $(dh_args) + +# Build architecture-dependent files here. +binary-arch: build-arch install + dh_testdir -a + dh_testroot -a +# dh_installdebconf -a + dh_installexamples -a + -dh_icons -a || dh_iconcache -a +# dh_installmime -a + dh_installchangelogs -a + for i in $(p_dev) $(p_dbg); do \ + rm -rf debian/$$i/usr/share/doc/$$i; \ + ln -s $(p_base) debian/$$i/usr/share/doc/$$i; \ + done + for i in $(p_lbase); do \ + rm -rf debian/$$i/usr/share/doc/$$i; \ + ln -s $(p_lmin) debian/$$i/usr/share/doc/$$i; \ + done + for i in $(p_ldev) $(p_ldbg) $(p_lib); do \ + rm -rf debian/$$i/usr/share/doc/$$i; \ + ln -s $(p_lbase) debian/$$i/usr/share/doc/$$i; \ + done + -find debian ! -perm -200 -print -exec chmod +w {} \; +ifneq ($(with_tk),yes) + rm -f $(d_lbase)/$(scriptdir)/lib-dynload/_tkinter.$(DEB_HOST_MULTIARCH).so +endif +ifneq ($(with_gdbm),yes) + rm -f $(d_lbase)/$(scriptdir)/lib-dynload/gdbm.$(DEB_HOST_MULTIARCH).so +endif + + find $(d_ldbg) $(d_ldev) -name '*.a' ! -type l \ + | xargs -n 1 $(DEB_HOST_GNU_TYPE)-objcopy -p --remove-section=.gnu.lto_.* + dh_strip -a -N$(p_dbg) -N$(p_ldbg) -Xdebug -Xdbg --dbg-package=$(p_dbg) + mkdir -p $(d_dbg)/usr/share/gdb/auto-load/usr/bin + cp Tools/gdb/libpython.py $(d_dbg)/usr/share/gdb/auto-load/usr/bin/$(PVER)-gdb.py + ln -sf $(PVER)-gdb.py $(d_dbg)/usr/share/gdb/auto-load/usr/bin/$(PVER)-dbg-gdb.py + mkdir -p $(d_dbg)/usr/share/gdb/auto-load/usr/lib/$(DEB_HOST_MULTIARCH) + ln -sf ../../bin/$(PVER)-gdb.py \ + $(d_dbg)/usr/share/gdb/auto-load/usr/lib/$(DEB_HOST_MULTIARCH)/lib$(PVER).so.1.0-gdb.py + ln -sf ../../bin/$(PVER)-gdb.py \ + $(d_dbg)/usr/share/gdb/auto-load/usr/lib/$(DEB_HOST_MULTIARCH)/lib$(PVER)_d.so.1.0-gdb.py + dh_link -a + dh_compress -a -X.py + dh_fixperms -a + + : # make python scripts starting with '#!' executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch' ! -perm 755`; do \ + if head -1 $$i | grep -q '^#!'; then \ + chmod 755 $$i; \ + echo "make executable: $$i"; \ + fi; \ + done + + dh_makeshlibs -p$(p_lib) -V '$(p_lib)' + dh_makeshlibs -p$(p_ldbg) -V '$(p_ldbg)' +# don't include the following symbols, found in extensions +# which either can be built as builtin or extension. + sed -ri '/^ (_check_|asdl_|fast_save_|init)/d' \ + $(d_lib)/DEBIAN/symbols $(d_ldbg)/DEBIAN/symbols + dh_shlibdeps -p$(p_min) -- -dPre-Depends + dh_shlibdeps -a -N$(p_min) + dh_installdeb -a + dh_gencontrol -a -- $(arch_substvars) + dh_md5sums -a + dh_builddeb -a + +# rules to patch the unpacked files in the source directory +# --------------------------------------------------------------------------- +# various rules to unpack addons and (un)apply patches. +# - patch / apply-patches +# - unpatch / reverse-patches + +patchdir = debian/patches + +glibc_version := $(shell dpkg -s locales | awk '/^Version:/ {print $$2}') +broken_utimes := $(shell dpkg --compare-versions $(glibc_version) lt 2.3.5 && echo yes || echo no) + +$(patchdir)/series: $(patchdir)/series.in + cpp -E \ + -D$(derivative) \ + $(if $(filter $(broken_utimes),yes),-DBROKEN_UTIMES) \ + $(if $(filter $(with_fpectl),yes),-DWITH_FPECTL) \ + -Darch_os_$(DEB_HOST_ARCH_OS) -Darch_$(DEB_HOST_ARCH) \ + -o - $(patchdir)/series.in \ + | egrep -v '^(#.*|$$)' > $(patchdir)/series + +patch: stamps/stamp-patch +stamps/stamp-patch: $(patchdir)/series + dh_testdir + uname -a + @echo USER=$$USER, LOGNAME=$$LOGNAME + QUILT_PATCHES=$(patchdir) quilt push -a || test $$? = 2 + rm -rf autom4te.cache configure + autoconf + mkdir -p stamps + echo ""; echo "Patches applied in this version:" > stamps/pxx + for i in $$(cat $(patchdir)/series); do \ + echo ""; echo "$$i:"; \ + sed -n 's/^# *DP: */ /p' $(patchdir)/$$i; \ + done >> stamps/pxx + mv stamps/pxx $@ + + dh_autotools-dev_updateconfig + + : # don't build pgen for cross builds, adjust timestamps + touch Parser/acceler.c Parser/grammar1.c Parser/listnode.c \ + Parser/node.c Parser/parser.c Parser/parsetok.c Parser/bitset.c \ + Parser/metagrammar.c Parser/firstsets.c Parser/grammar.c \ + Parser/pgen.c + touch Objects/obmalloc.c Python/mysnprintf.c Python/pyctype.c \ + Parser/tokenizer_pgen.c Parser/printgrammar.c Parser/pgenmain.c + @sleep 0.1 + touch Grammar/Grammar + @sleep 0.1 + touch Include/graminit.h + @sleep 0.1 + touch Python/graminit.c + ln -sf site-packages Lib/dist-packages + +reverse-patches: unpatch +unpatch: + QUILT_PATCHES=$(patchdir) quilt pop -a -R || test $$? = 2 + rm -f stamps/stamp-patch $(patchdir)/series + rm -rf configure autom4te.cache + rm -f Lib/dist-packages + +update-patches: $(patchdir)/series + export QUILT_PATCHES=$(patchdir); \ + export QUILT_REFRESH_ARGS="--no-timestamps --no-index -pab"; \ + export QUILT_DIFF_ARGS="--no-timestamps --no-index -pab"; \ + while quilt push; do quilt refresh; done + +binary: binary-indep binary-arch + +.NOTPARALLEL: +.PHONY: control-file configure build clean binary-indep binary-arch binary install + +# Local Variables: +# mode: makefile +# end: --- python2.7-2.7.15.orig/debian/script.py +++ python2.7-2.7.15/debian/script.py @@ -0,0 +1,61 @@ +#! /usr/bin/python + +# Copyright (C) 2012 Colin Watson . +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject +# to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +"""Trivial script(1) workalike, but without reading from standard input.""" + +import os +import pty +import select +import sys + +filename = sys.argv[1] +command = sys.argv[2] + +pid, master = pty.fork() +if pid == 0: # child + os.execlp("sh", "sh", "-c", command) + +# parent +with open(filename, "w") as logfile: + try: + while True: + rfds, _, _ = select.select([master], [], []) + if master in rfds: + data = os.read(master, 65536) + os.write(1, data) + logfile.write(data) + logfile.flush() + except (IOError, OSError): + pass + +pid, status = os.wait() +returncode = 0 +if os.WIFSIGNALED(status): + returncode = -os.WTERMSIG(status) +elif os.WIFEXITED(status): + returncode = os.WEXITSTATUS(status) +else: + # Should never happen + raise RuntimeError("Unknown child exit status!") +os.close(master) +sys.exit(returncode) --- python2.7-2.7.15.orig/debian/sitecustomize.py.in +++ python2.7-2.7.15/debian/sitecustomize.py.in @@ -0,0 +1,7 @@ +# install the apport exception handler if available +try: + import apport_python_hook +except ImportError: + pass +else: + apport_python_hook.install() --- python2.7-2.7.15.orig/debian/source.lintian-overrides +++ python2.7-2.7.15/debian/source.lintian-overrides @@ -0,0 +1,14 @@ +# this is conditional in the rules file +python2.7 source: debhelper-script-needs-versioned-build-depends dh_icons (>= 5.0.51~) + +# generated during the build +python2.7 source: quilt-build-dep-but-no-series-file + +# doesn't support any newer versions +python2.7 source: build-depends-on-versioned-berkeley-db + +# using the system libffi +python2.7 source: outdated-autotools-helper-file + +# patches are applied conditionally +python2.7 source: patch-file-present-but-not-mentioned-in-series --- python2.7-2.7.15.orig/debian/source.lintian-overrides.in +++ python2.7-2.7.15/debian/source.lintian-overrides.in @@ -0,0 +1,14 @@ +# this is conditional in the rules file +@PVER@ source: debhelper-script-needs-versioned-build-depends dh_icons (>= 5.0.51~) + +# generated during the build +@PVER@ source: quilt-build-dep-but-no-series-file + +# doesn't support any newer versions +@PVER@ source: build-depends-on-versioned-berkeley-db + +# using the system libffi +@PVER@ source: outdated-autotools-helper-file + +# patches are applied conditionally +@PVER@ source: patch-file-present-but-not-mentioned-in-series --- python2.7-2.7.15.orig/debian/source/format +++ python2.7-2.7.15/debian/source/format @@ -0,0 +1 @@ +1.0 --- python2.7-2.7.15.orig/debian/tests/control +++ python2.7-2.7.15/debian/tests/control @@ -0,0 +1,19 @@ +Tests: testsuite +Depends: build-essential, locales, python2.7-dev, libpython2.7-testsuite, python-gdbm +# test_zipfile wants to write +Restrictions: needs-root + +Tests: testsuite-dbg +Depends: build-essential, locales, python2.7-dev, python2.7-dbg, libpython2.7-testsuite, python-gdbm-dbg +# test_zipfile wants to write +Restrictions: needs-root + +Tests: failing-tests +Depends: build-essential, locales, python2.7-dev, libpython2.7-testsuite, python-gdbm +# test_zipfile wants to write +Restrictions: needs-root allow-stderr + +Tests: failing-tests-dbg +Depends: build-essential, locales, python2.7-dev, python2.7-dbg, libpython2.7-testsuite, python-gdbm-dbg +# test_zipfile wants to write +Restrictions: needs-root allow-stderr --- python2.7-2.7.15.orig/debian/tests/failing-tests +++ python2.7-2.7.15/debian/tests/failing-tests @@ -0,0 +1,126 @@ +#!/bin/sh + +set -e + +if [ "$(whoami)" = root ]; then + if [ -n "$SUDO_USER" ] && getent passwd "$SUDO_USER" > /dev/null; then + su_user="$SUDO_USER" + else + su_user=nobody + fi + + if [ -e /etc/default/apport ]; then + # stop apport + service apport stop 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + fi +fi + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chmod go+rx $ADTTMP + chown $su_user:nogroup $tmphome +fi +ls -la $ADTTMP + +# no root access needed after this point + +debian_dir=$(dirname $(dirname $0)) + +export LOCPATH=$(pwd)/locales +sh $debian_dir/locale-gen + +export LANG=C + +arch=$(dpkg --print-architecture) +vendor=$(dpkg-vendor --query Vendor) + +TESTPYTHON="python2.7 -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS= + +# test_cpickle: starts to fail with 2.7.11, see http://bugs.python.org/issue25698 +TESTEXCLUSIONS="$TESTEXCLUSIONS test_cpickle" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: failing tests test_parse_makefile_base, test_parse_makefile_literal_dollar +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_gdb: not run for the optimized build +TESTEXCLUSIONS="$TESTEXCLUSIONS test_gdb" + +# test_threading_local: fails in the Debian CI environment, but even +# succeeds there when re-run. See +# http://ci.debian.net/data/packages/unstable/amd64/p/python2.7/20141121_061940.autopkgtest.log.gz +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_threading_local" +esac + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +# for some reason, this fails on s390x only, starting in 2.7.14rc1 ... +case "$(uname -m)" in s390*) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_regrtest" +esac + +# testsuite not ready for OpenSSL 1.2 ... +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_ftplib test_ssl" +esac + +if [ "$su_user" = nobody ]; then + log=/dev/null +else + log=testsuite.log +fi + +# run some tests separately in it's own run. These succeed locally, +# but fail on the test setup. +SEPARATE_TESTS= +case "$arch" in + amd64) + ;; + i386) + SEPARATE_TESTS="$SEPARATE_TESTS test_io" + ;; +esac + +script=$debian_dir/script.py + +echo "Running the failing tests with the standard interpreter:" +progressions= +for tst in $TESTEXCLUSIONS; do + if [ -f "$script" ]; then + cmd="HOME=$tmphome python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $tst\"" + else + cmd="HOME=$tmphome $TESTPYTHON $TESTOPTS $tst" + fi + + echo "Running $tst ..." + if [ "$(whoami)" = root ]; then + echo "su -s /bin/sh -c $cmd $su_user" + if su -s /bin/sh -c "$cmd" $su_user; then + progressions="$progressions $tst" + else + : + fi + else + echo "$cmd" + if eval $cmd; then + progressions="$progressions $tst" + else + : + fi + fi +done + +if [ -n "$progressions" ]; then + echo "Tests run: $TESTEXCLUSIONS" + echo "Progressions:$progressions" +fi + +exit 0 --- python2.7-2.7.15.orig/debian/tests/failing-tests-dbg +++ python2.7-2.7.15/debian/tests/failing-tests-dbg @@ -0,0 +1,119 @@ +#!/bin/sh + +set -e + +if [ "$(whoami)" = root ]; then + if [ -n "$SUDO_USER" ] && getent passwd "$SUDO_USER" > /dev/null; then + su_user="$SUDO_USER" + else + su_user=nobody + fi + + if [ -e /etc/default/apport ]; then + # stop apport + service apport stop 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + fi +fi + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chmod go+rx $ADTTMP + chown $su_user:nogroup $tmphome +fi +ls -la $ADTTMP + +# no root access needed after this point + +debian_dir=$(dirname $(dirname $0)) + +export LOCPATH=$(pwd)/locales +sh $debian_dir/locale-gen + +export LANG=C + +arch=$(dpkg --print-architecture) +vendor=$(dpkg-vendor --query Vendor) + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chown $su_user $tmphome +fi + +TESTPYTHON="python2.7-dbg -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS= + +# test_cpickle: starts to fail with 2.7.11, see http://bugs.python.org/issue25698 +TESTEXCLUSIONS="$TESTEXCLUSIONS test_cpickle" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: failing tests test_parse_makefile_base, test_parse_makefile_literal_dollar +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_threading_local: fails in the Debian CI environment, but even +# succeeds there when re-run. See +# http://ci.debian.net/data/packages/unstable/amd64/p/python2.7/20141121_061940.autopkgtest.log.gz +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_threading_local" +esac + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +# testsuite not ready for OpenSSL 1.2 ... +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_ftplib test_ssl" +esac + +# TODO: test_ctypes fails on arm64 on the debug build +echo "uname: $(uname -a)" +case "$(uname -m)" in armv8*|aarch64*) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_ctypes" +esac + +if [ "$su_user" = nobody ]; then + log=/dev/null +else + log=testsuite-dbg.log +fi + +script=$debian_dir/script.py + +echo "Running the failing tests with the standard interpreter:" +progressions= +for tst in $TESTEXCLUSIONS; do + if [ -f "$script" ]; then + cmd="HOME=$tmphome python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $tst\"" + else + cmd="HOME=$tmphome $TESTPYTHON $TESTOPTS $tst" + fi + + echo "Running $tst ..." + if [ "$(whoami)" = root ]; then + echo "su -s /bin/sh -c $cmd $su_user" + if su -s /bin/sh -c "$cmd" $su_user; then + progressions="$progressions $tst" + else + : + fi + else + echo "$cmd" + if eval $cmd; then + progressions="$progressions $tst" + else + : + fi + fi +done + +if [ -n "$progressions" ]; then + echo "Tests run: $TESTEXCLUSIONS" + echo "Progressions:$progressions" +fi + +exit 0 --- python2.7-2.7.15.orig/debian/tests/testsuite +++ python2.7-2.7.15/debian/tests/testsuite @@ -0,0 +1,125 @@ +#!/bin/sh + +set -e + +env + +if [ "$(whoami)" = root ]; then + if [ -n "$SUDO_USER" ] && getent passwd "$SUDO_USER" > /dev/null; then + su_user="$SUDO_USER" + else + su_user=nobody + fi + + if [ -e /etc/default/apport ]; then + # stop apport + service apport stop 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + fi +fi + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chmod go+rx $ADTTMP + chown $su_user:nogroup $tmphome +fi +ls -la $ADTTMP + +# no root access needed after this point + +debian_dir=$(dirname $(dirname $0)) + +export LOCPATH=$(pwd)/locales +sh $debian_dir/locale-gen + +export LANG=C + +arch=$(dpkg --print-architecture) +vendor=$(dpkg-vendor --query Vendor) + +TESTPYTHON="python2.7 -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS="-x" + +# test_cpickle: starts to fail with 2.7.11, see http://bugs.python.org/issue25698 +TESTEXCLUSIONS="$TESTEXCLUSIONS test_cpickle" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: failing tests test_parse_makefile_base, test_parse_makefile_literal_dollar +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_ensurepip: module disabled in Debian +TESTEXCLUSIONS="$TESTEXCLUSIONS test_ensurepip" + +# test_gdb: not run for the optimized build +TESTEXCLUSIONS="$TESTEXCLUSIONS test_gdb" + +# test_threading_local: fails in the Debian CI environment, but even +# succeeds there when re-run. See +# http://ci.debian.net/data/packages/unstable/amd64/p/python2.7/20141121_061940.autopkgtest.log.gz +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_threading_local" +esac + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +# for some reason, this fails on s390x only, starting in 2.7.14rc1 ... +case "$(uname -m)" in s390*) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_regrtest" +esac + +# testsuite not ready for OpenSSL 1.2 ... +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_ftplib test_ssl" +esac + +if [ "$su_user" = nobody ]; then + log=/dev/null +else + log=testsuite.log +fi + +# run some tests separately in it's own run. These succeed locally, +# but fail on the test setup. +SEPARATE_TESTS= +case "$arch" in + amd64) + ;; + i386) + SEPARATE_TESTS="$SEPARATE_TESTS test_io" + ;; +esac + +# several tests fail with configured proxy; we don't need internet access, so +# unset proxy variables +EXTRAENV="env -u https_proxy -u http_proxy -u no_proxy HOME=$tmphome" + +script=$debian_dir/script.py +if [ -f "$script" ]; then + cmd1="$EXTRAENV python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $TESTEXCLUSIONS $SEPARATE_TESTS\"" + cmd2="$EXTRAENV python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $SEPARATE_TESTS\"" +else + cmd1="$EXTRAENV $TESTPYTHON $TESTOPTS $TESTEXCLUSIONS $SEPARATE_TESTS" + cmd2="$EXTRAENV $TESTPYTHON $TESTOPTS $SEPARATE_TESTS" +fi + +echo "Running the python testsuite with the standard interpreter:" +if [ "$(whoami)" = root ]; then + echo "su -s /bin/sh -c $cmd1 $su_user" + su -s /bin/sh -c "$cmd1" $su_user + if [ -n "$SEPARATE_TESTS" ]; then + echo "su -s /bin/sh -c $cmd2 $su_user" + su -s /bin/sh -c "$cmd2" $su_user + fi +else + echo "$cmd1" + eval $cmd1 + if [ -n "$SEPARATE_TESTS" ]; then + echo "$cmd2" + eval $cmd2 + fi +fi --- python2.7-2.7.15.orig/debian/tests/testsuite-dbg +++ python2.7-2.7.15/debian/tests/testsuite-dbg @@ -0,0 +1,99 @@ +#!/bin/sh + +set -e + +if [ "$(whoami)" = root ]; then + if [ -n "$SUDO_USER" ] && getent passwd "$SUDO_USER" > /dev/null; then + su_user="$SUDO_USER" + else + su_user=nobody + fi + + if [ -e /etc/default/apport ]; then + # stop apport + service apport stop 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + fi +fi + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chmod go+rx $ADTTMP + chown $su_user:nogroup $tmphome +fi +ls -la $ADTTMP + +# no root access needed after this point + +debian_dir=$(dirname $(dirname $0)) + +export LOCPATH=$(pwd)/locales +sh $debian_dir/locale-gen + +export LANG=C + +arch=$(dpkg --print-architecture) +vendor=$(dpkg-vendor --query Vendor) + +TESTPYTHON="python2.7-dbg -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS="-x" + +# test_cpickle: starts to fail with 2.7.11, see http://bugs.python.org/issue25698 +TESTEXCLUSIONS="$TESTEXCLUSIONS test_cpickle" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: failing tests test_parse_makefile_base, test_parse_makefile_literal_dollar +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_ensurepip: module disabled in Debian +TESTEXCLUSIONS="$TESTEXCLUSIONS test_ensurepip" + +# test_threading_local: fails in the Debian CI environment, but even +# succeeds there when re-run. See +# http://ci.debian.net/data/packages/unstable/amd64/p/python2.7/20141121_061940.autopkgtest.log.gz +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_threading_local" +esac + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +# testsuite not ready for OpenSSL 1.2 ... +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_ftplib test_ssl" +esac + +# TODO: test_ctypes fails on arm64 on the debug build +echo "uname: $(uname -a)" +case "$(uname -m)" in armv8*|aarch64*) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_ctypes" +esac + +if [ "$su_user" = nobody ]; then + log=/dev/null +else + log=testsuite-dbg.log +fi + +# several tests fail with configured proxy; we don't need internet access, so +# unset proxy variables +EXTRAENV="env -u https_proxy -u http_proxy -u no_proxy HOME=$tmphome" + +script=$debian_dir/script.py +if [ -f "$script" ]; then + cmd="$EXTRAENV python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $TESTEXCLUSIONS\"" +else + cmd="$EXTRAENV $TESTPYTHON $TESTOPTS $TESTEXCLUSIONS" +fi +echo "Running the python testsuite with the debug enabled interpreter:" +if [ "$(whoami)" = root ]; then + echo "su -s /bin/sh -c $cmd $su_user" + su -s /bin/sh -c "$cmd" $su_user +else + echo "$cmd" + eval $cmd +fi --- python2.7-2.7.15.orig/debian/watch +++ python2.7-2.7.15/debian/watch @@ -0,0 +1,3 @@ +version=3 +opts=dversionmangle=s/.*\+//,uversionmangle=s/([abcr]+[1-9])$/~$1/ \ + http://www.python.org/ftp/python/(2\.7\.\d*)/Python-(2\.7[.\dabcr]*)\.tgz